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

标签 python python-3.x

问题

计算并打印给定正整数的阶乘。该整数可以大到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))

关于python - HackerRank Python 编译错误递归阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964612/

相关文章:

python - Python 中 NumPy 或 SciPy 中 Wolfram Mathematica 的模拟函数

python - 如何从任意大小的矩阵中分割每个 3x3 子矩阵?

python - Pig Hadoop Stream 帮助

python - 谷歌 BigQuery : creating a view via Python google-cloud-bigquery version 0. 27.0 与 0.28.0

python多处理/线程代码提前退出

Python:tqdm 进度条停留在 0%

python - 按下 tkinter 按钮即可调用函数

python - 从父类别 django rest 获取所有产品

python - 将数组切片为阶梯式连续 block 的 Python 方式是什么?

Python:为什么我的装饰器无法工作?