hackerrank problem runs fine in jupyter but fails in hackerrank - python

I'm not sure what's going on with this problem.
I place the exact same code in a jupyter notebook and everything runs fine. But when I place the code in Hackerrank it does not return any output.
Does anyone spot the error here?
Sample:
6 4
give me one grand today night
give one grand today
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the checkMagazine function below.
def checkMagazine(magazine, note):
ds = Counter(magazine)
for m in note:
ds[m] = ds[m] - 1
if ds[m] < 0 or ds[m] is None: return 'No'
return 'Yes'
if __name__ == '__main__':
mn = input().split()
m = int(mn[0])
n = int(mn[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
checkMagazine(magazine, note)

This code returns but doesn't print the output to stdout that the HR code runner is looking for. Try print(checkMagazine(magazine, note)).
In general, HR is a bit fussy about IO. Data will be read through stdin and will be printed to stdout, often in bizarre formats like "Yes" or "Impossible!" for a function that would normally return a boolean.

Related

Python Staircase (Hackerrank)

I'm trying to solve a problem in Hacker rank and they gave me a staircase challenge. I don't see the difference between my output and theirs. Could anyone help me out?
Here's the link to my problem: https://www.hackerrank.com/challenges/staircase/problem.
Here's the code I wrote(only the function, rest were already written):
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
for x in range(n, 0, -1):
print(" "*(x-1),"#"*(n-x+1))
if __name__ == '__main__':
n = int(input())
staircase(n)
The output screen on the website:

Unexpected Python behaviour - function fails to terminate after return statement

I wrote a function to traverseMountain(altitude, stepsleft, substring) as helper function to part of a solution to one of the hackerrank problems. I consider it better practice to test functions as I write them, and this is where I am encountering my problem.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
altitude = 0
mountiansCount = 0
valleysCount = 0
def tailRecurseSolution(stepsleft, substring):
head, tail = substring[0], substring[1:]
if (head == 'U'):
mountiansCount+=1
traverseMountain(n-1, tail)
if (head == 'D'):
traverseValley(altitude+1, n-1, tail)
# return valleysCount
def traverseMountain(altitude, stepsleft, substring):
head, tail = substring[0], substring[1:]
if (head=="D"):
altitude-=1
if (head=="U"):
altitude+=1
stepsleft-=1
if (altitude<=0 or stepsleft<=0 or (not tail)):
x = stepsleft
return x
elif (altitude>0 and stepsleft>0 and tail):
traverseMountain(altitude, stepsleft,tail)
#def traverseValley(alt, stepsleft, substring):
# return x
if __name__ == '__main__':
altitude = 0
stepsleft = 99
path = "UUUDUDDD"
print(traverseMountain(altitude, stepsleft, path))
You can ignore the countingValleys function as its imcomplete and not being called.
What I was expecting to happen was for the function traverseMountian to meet the if conditional, and would step into the block upon the last recursive call (when altitude variable is 0 or the tail is the empty string) and then exit the function and return the value of the stepsLeft variable.
What I am witnessing is that my debugger steps inside of that if statement, but immediately jumps to inside the elif statement (I do not understand why it would do that) and the variables I receive are reset?
I wanted to make a post here in case it's intended behaviour of the code
I've spent a lot of time today just trying to figure out why Python does not terminate the function after the return statement. I've played out with the conditionals, the placing of the return statement etc. but without success.
You're returning x but in your recursion call you're not doing anything with the return value.
You might want return traverseMountain(altitude, stepsleft,tail) as your last line in traverseMountain?

Code trouble with python

I'm having some trouble here. For my CS assignment, I have to have python take data from a file on my pc and run the data through my program.
So, this code works fine on http://repl.it/languages/Python, but not in python. I'm assuming because my line of code has some Python 2.0 lines of code? I can't seem to fix it. Can you guys help? And, another small question except this one. I have to input some code in my program to take data from a file and run it through my program as I stated above. I have this.
import math
def mean(values):
average = sum(values)*1.0/len(values)
return average
def deviation(values):
length = len(values)
m = mean(values)
total_sum = 0
for i in range(length):
total_sum += (values[i]-m)**2
root = total_sum*1.0/length
return math.sqrt(root)
def median(values):
if len(values)%2 != 0:
return sorted(values)[len(values)/2]
else:
midavg = (sorted(values)[len(values)/2] + sorted(values)[len(values)/2-1])/2.0
return midavg
def main():
x = [15, 17, 40, 16, 9]
print mean(x)
print deviation(x)
print median(x)
main()
How do I specifically have the program take data from the file and run it through my program? The data is just a bunch of numbers, by the way. It's been giving me trouble for some hours now. Thanks if you can help out.
This is what I know about the opening/closing file stuff so far
f = open("filename.txt")
data = f.readlines()
f.close()
Apparently you are using python2.x:
I'm assuming because my line of code has some Python 2.0 lines of code?
So yes, you do have a problem: In python3.x, print became a function.
Thus, your prints need to be changed:
print mean(x)
print deviation(x)
print median(x)
Becomes
print(mean(x))
print(deviation(x))
print(median(x))
Also, your part about opening and closing files is unclear.

Python algorithm output troubleshoot

I have attached a python 2.7 script to answer question number 2 from the following link: http://labs.spotify.com/puzzles/
My attempt to solve is currently being met with a "wrong answer" reply, yet my code successfully works for the sample inputs on the site. I have tried modifying it to return and even print a list of the top m songs, instead of printing them out individually, but that did not work either. Any help or ideas would be great. Thanks in advance
import sys
def main():
line1 = sys.stdin.readline().split()
total_songs = int(line1[0])-1
num_songs_return = int(line1[1])
data = sys.stdin.read().split()
while(total_songs >= 0):
data[2*total_songs]= float(data[2*total_songs]) * (total_songs+1)
total_songs-=1
answers = [(data[a], data[a+1]) for a in range(0,len(data),2)]
answers.sort(reverse=True)
for n in range(num_songs_return):
print answers[n][1]
main()

Run Time Error Exited with error status 1

The problem is this :
I tried to solve it and I think I did too but when I mailed it for evaluation it says
We have tested your solution, and while doing so we unfortunately
discovered the following error:
Run Time Error
Exited with error status 1
Here is my code :
import re
import sys
def fun():
for ind in ratio:
max_num = ratio_list[0]
if ratio[ind] == max_num:
print ind
ratio_list.remove(ratio_list[0])
hits = []
song = []
n,m = raw_input().split(' ',1)
for i in range(0,int(n)):
h,n = raw_input().split(" ",1)
is_number = isinstance( int(h), int )
is_string = len(n)<=30 and bool(re.match('[a-z_0-9]+$', n))
if not(is_number and is_string):
sys.exit("Error");
hits.append(int(h))
song.append(n)
ratio = {}
ratio_list = []
f_of_i = hits[0]
counter = 1
index = 0
for hit in hits:
ratio_list.append(hit*counter)
ratio[song[index]] = hit*counter
index = index +1
counter = counter +1
ratio_list.sort()
ratio_list.reverse()
for j in range(0,int(m)):
fun()
What am I doing wrong ? I am curious why the solution is unacceptable killing me.
I suspect you're hitting
sys.exit("Error");
As explained in the documentation:
Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1.
Might be worth relaxing your input validation a little? Right now it's so strict it would reject inputs that to me appear within the spec (say if there were two spaces between the play count and the song title).
Another possibility is that your code raises an exception. On my machine this also results in an exit code of 1.
Finally, while not a bug, I think the way you reuse the variable called n is questionable style.

Categories

Resources