Skip to main content
 首页 » 编程设计

python之HackerRank Python 编译错误递归阶乘

2025年05月04日7sky-heaven

问题

计算并打印给定正整数的阶乘。整数可以大到 100。

Here's a link to the problem

我的努力

我在其他编译器上尝试过解决方案,它们在其他编译器上运行良好,但在 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))