Problem
Calculate and print the factorial of a given positive integer. The integer can be as large as 100
.
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.