【发布时间】:2017-08-12 06:37:37
【问题描述】:
我已经实现了一个函数,通过使用递归创建一个列表来计算从 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 的初学者。提前致谢。
【问题讨论】:
-
你的代码有什么问题?
-
嗯,我在实现打印阶乘“*”的功能时遇到了麻烦。 @DYZ
-
@eye 具体是哪一部分的问题?您的代码甚至没有尝试打印一颗星。
-
在发布问题之前请阅读stackoverflow.com/help/how-to-ask。
-
@eye 尝试按顺序遍历您返回的列表并调用
print("*" * k),其中k是您列表中的任意值。 Python 中的"*" * k表示k的重复项"*"相互连接。
标签: python list recursion factorial