Python 使用递归查找数的阶乘的程序

Python Program to Find Factorial of Number Using Recursion

一个数的阶乘是从 1 到该数的所有整数的乘积。

例如6的阶乘为12345*6 = 720。负数没有定义阶乘零的阶乘是一,0! = 1.

def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

num = 7

# check if the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of", num, "is", recur_factorial(num))

如何计算 Python 中整数的阶乘?请注意,阶乘函数仅针对正整数定义;因此,您还应该检查 n >= 0 和 isinstance(n, int)。否则,分别提高一个ValueError或一个TypeError

def factorial(n): 
    if(not isinstance(n, int) or n < 0):
       raise ValueError("Invalid argument")

    if (n==1 or n==0):          
        return 1      
    else:          
        return (n * factorial(n - 1)) 
  
# Driver Code 
num = int(input("Please enter a number"))
print("Factorial : ",factorial(num))

I would like help just to know how to read the entries and call the functions

为此,您可以在函数下方添加以下代码:

# main program
method = {
    "IV": add_node,
    "IA": add_edge,
    "RV": delete_node,
    "RA": delete_edge
}
numinputlines = int(input())
for _ in range(numinputlines):
    instruction, *rest = input().split()
    if len(rest) == 3:  # There is a cost:
        rest[-1] = int(rest[-1])
    method[instruction](*rest)

method 字典有助于将 2 个字母的代码转换为需要调用的方法。由于这些方法的参数顺序相同,您只需将它们捕获到列表 rest 中,并在传递参数时“解压”该列表。只有一件特别的事情需要照顾。两个方法都得到一个cost参数,而且必须是数字类型。由于输入被读取为字符串,因此您需要将该成本字符串转换为数字。 if 语句处理这种情况。

这应该可以回答您的问题,但并未完成练习。您仍然需要调试代码。例如,当前您的代码将在您提供的示例输入中引发异常——顶点“B”在添加 IV B.

之前在 IA B A 1 中被引用

此外,您还需要添加代码来生成输出。

但由于您的问题是关于捕获输入和调用函数,所以我将剩下的问题留给您解决。