HackerRank Python Compile Error Recursion Factorial - python

Problem
Calculate and print the factorial of a given positive integer. The integer can be as large as 100.
Here's a link to the problem
My effort
I have tried solutions on other compilers, they are working fine on other compilers, but on hackerrank its not working saying compile time error
# Enter your code here. Read input from STDIN. Print output to STDOUT
def fac(n):
return 1 if (n < 1) else n * fac(n-1)
no = int(raw_input())
print fac(no)
Any help would be appreciated

This solution works just fine for Python 2 - I ran your code on Hackerrank and it passed all the test cases.
So, the compilation error is shown if the code is compiled with Python 3.
no = int(raw_input())
NameError: name 'raw_input' is not defined
That's true because raw_input must be replaced with input() in Python 3.
If the code with the correction is executed afterwards then there's another issue:
print fac(no)
^
SyntaxError: invalid syntax
Again, just add parentheses around fac(no) and then the code compiles and passes all the tests:
So, the full code is below:
def fac(n):
return 1 if (n < 1) else n * fac(n-1)
no = int(input())
print (fac(no))

Related

How to get rid of run time error on code chef

The following code works fine on both the jupiter notebook and the pycharm but its showing runtime error on codechef. The code is to check whether the permutation is ambiguous or not.
for i in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
p=l[:]
for j in range(n):
p[l[j]-1]=j+1
if(p==l):
print("ambiguous")
else:
print("not ambiguous")
Welcome to Stack Overflow!
When posting, it usually helps to add more information, such as the error message itself. Regardless, I pasted your code into Python and I've deduced that the problem arises from the input() statement- I'm not sure what 'code chef' is, but it probably doesn't know that the user should input an integer into the input() prompt.
Therefore, a workaround is to hardcode your inputs as variables:
input1 = "5"
input2 = ...
for i in range(int(input1)):
n=int(input2)
...

EOF error python 3

def reverse_number(x):
return x[::-1]
number_of_sums = int(input())
for i in range(number_of_sums):
s1 = input().split()
print(int(reverse_number(s1[0])) + int(reverse_number(s1[1])))
I have the following code, which should be a solution to a SPOJ problem. It compiles fine and works for examples that I provide, but as soon as I submit it says that it found an EOF error.
It points me to line 5 in the code, and I believe I understand why. When I use input() I try to get the whole line, right? So, how would I go ahead to only get the number? If that is the problem of course, it might be something else that ruins the code.
def reverse_number(x):
return x[::-1]
try:
number_of_sums = int(input())
for i in range(number_of_sums):
s1 = input().split()
if len(s1) > 0:
print(int(reverse_number(s1[0])) + int(reverse_number(s1[1])))
except ValueError:
print("Invalid Input")
Now, if you run the program and submit it will throw error stating "Invalid Input". Apart from adding the try block, also included the condition check for s1 as you might encounter an "Index out of range" error if not given proper input.
It may be that the grader/engine that checks the code is running Python2, in which case you could change to:
number_of_sums = int(raw_input())
before submitting (and a similar change on line 8).

Getting NZEC error for python:

I am a newbie in python, started learning the language a week ago tried to test it out in codechef...
Here is the question link: https://www.codechef.com/problems/COOMILK
So with what i understood so far i typed the following piece of code..
t=int(input())
f=[]
if(t >= 1 and t <= 50):
for each in range(t):
n=int(input())
if(n >= 1 and n <=50):
m=input().split()
for i in range(len(m)):
if(m[i]=='milk'):
q=1
elif(len(m)==1 and m[0]=='cookie'):
q=0
break
elif(m[i]=='cookie' and m[i+1]!='milk'):
q=0
break
f.append(q)
for i in f:
if(i==1):
print("YES")
elif(i==0):
print("NO")
So apart from the n constraint being not checked during the input, what actually showed was a runtime error.
New to this can someone explain it clearly why i am getting the nzec error?
Compiled it on my own and for all the test cases it worked properly but does not compile on code chef.. any help would be appreciated.
What i have gathered from the net is that there is no raw_input in python 3.x that i am using currently, so just a friendly reminder here....
NZEC stands for "Non Zero Exit Code". It occurs when you encounter a runtime error usually index out of bound error.
There is a mistake in the 14th line of your code:
elif (m[i]=='cookie' and m[i+1]!='milk'):
what if i+1 is out of range?
e.g.,
Consider the input to be:
1
3
cookie milk cookie
1 is the number of testcases.
3 is the number of elements in the
list.
'cookie milk cookie' composes the list elements.
When the value of i is 2 and your code's 14th line comes to execution, it will generate an index out of bound error(because m[i+1] i.e. m[3] doesn't exist!) which is a type of runtime error and thus generates NZEC error.
Add this code after the 7th line of your code:
if m[-1]=='cookie':
f.append(0)
continue
You could try using
try:
#working code
except Exception:
pass
Try and catch exception for java code.

Why does this Python code give Runtime Error(NZEC)?

I already read the other questions and answers but couldn't implement any of the solutions to my code. I'm still clueless about the reason why this code gives a runtime error.
I'm trying to submit the code on CodeChef, yet it gives the Runtime Error(NZEC), although the code runs flawlessly on my console for some inputs. Here's my code:
def GetSquares(base):
if not base or base < 4:
return 0
else:
x = (base - 4) - (base % 2) + 1
return x + GetSquares(base - 4)
num_test = int(input())
for test in range(num_test):
base = int(input())
print (int(GetSquares(base)))
Codechef's explanation for NZEC:
NZEC stands for Non Zero Exit Code. For C users, this will be
generated if your main method does not have a return 0; statement.
Other languages like Java/C++ could generate this error if they throw
an exception.
The problem I'm trying to solve:
https://www.codechef.com/problems/TRISQ
The problem description says that the input is constrained to be < 10^4. That's 10,000! Your code will need to make 10,000/4 = 2500 recursive calls to GetSquares, that's a lot! In fact, it's so much that it's going to give you, fittingly, this error:
RuntimeError: maximum recursion depth exceeded
You're going to have to think of a better way to solve the problem that doesn't involve so much recursion! Because you're doing this coding challenge, I'm not going to give a solution in this answer as that would sort of defeat the purpose, but if you'd like some prodding towards an answer, feel free to ask.
The question puts a constraint on the value of 'B' which is 10000 at max, which means there are a lot of recursive calls and giving a runtime error. Try solving using iteration.

Runtime Error (NZEC) - Python / Codechef

I'm getting started with Codechef. I submitted following code in python to solve this question.
The code below works fine with codechef's online (python) IDE as well as my local IDE. But, when I submit it on codechef, it results in Runtime Error (NZEC). Can someone explain to me the reason behind this?
withdrawCash = int(input())
totalCash = int(input())
if withdrawCash < totalCash and withdrawCash % 5 is 0:
totalCash = (totalCash - withdrawCash) - 0.5
print(totalCash)
The problem supplies both the inputs in a single line. Your code waits for input in 2 lines. Change it to:
withdrawCash,totalCash = map(int,raw_input.split())
NZEC (Non Zero Exit Code) occurs when your code doesn't return zero on exit. It can happen due to a number of reasons, but if splitting the input doesn't solve the problem, add an exception for EOFerror. Just write:
try:
withdrawCash = int(input().split()) # raw_input in the case of Python 2
except EOFerror:
print ("exit") # this is jst a pseudo statement `
Use indentation properly. I am currently using an android app of stack exchange in which writing code is not so easy. codechef is pretty poor when it comes to Python. Switch to any other lang for CP.
Try directly submitting the code without running it on Codechef ide because it with me also it showed the same but when I submitted directly I got submitted successfully. so Directly submit your code.

Categories

Resources