问题
计算并打印给定正整数的阶乘。该整数可以大到100
。
我的努力
我已经在其他编译器上尝试过解决方案,它们在其他编译器上工作正常,但在 hackerrank 上它不起作用,说编译时错误
# 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)
如有任何帮助,我们将不胜感激
最佳答案
此解决方案适用于 Python 2 - 我在 Hackerrank 上运行了您的代码并且它通过了所有测试用例。
因此,如果使用Python 3编译代码,则会显示编译错误。
no = int(raw_input())
NameError: name 'raw_input' is not defined
确实如此,因为在 Python 3 中,raw_input
必须替换为 input()
。
如果之后执行更正后的代码,则会出现另一个问题:
print fac(no)
^
SyntaxError: invalid syntax
同样,只需在 fac(no)
两边添加括号,然后代码就会编译并通过所有测试:
所以,完整的代码如下:
def fac(n):
return 1 if (n < 1) else n * fac(n-1)
no = int(input())
print (fac(no))
关于python - HackerRank Python 编译错误递归阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964612/