我已经实现了一个函数,通过使用递归创建列表来计算从 1 到 n(其中 n 是用户输入)的阶乘。我想通过定义一个在主函数内递归调用自身的新函数,为 1 到 n 范围内的每个整数 k 打印一行 k 阶乘星。如果 n=3,输出应如下所示:
*
**
******
这是迄今为止我使用递归计算阶乘的代码:
#Ask the user to input a positive integer n
n=int(input("Enter positive integer: "))
#Defining a function to calculate the factorial of a input number
def factorialN(n):
#Defining the base case
if n==1:
#If it satisfy the base condition return a list containing 1
return [1]
#Calling the function factorialN() recursively
list_1=factorialN(n-1)
new_factorial=list_1[-1]*n
list_1.append(new_factorial)
return list_1
所以我很难实现打印阶乘星星(“*”)的功能。非常感谢任何帮助,因为我是 Python 的初学者。提前致谢。
最佳答案
您编写的函数返回一个列表,其中包含哪一行应有多少个“*”。
对于n = 3
,它返回:[1, 2, 6]
打印它们:
for x in output:
print('*'*x) # print * x times
关于 python : printing lines of factorial "*" through recursion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45647310/