python : printing lines of factorial "*" through recursion

标签 python list recursion factorial

我已经实现了一个函数,通过使用递归创建列表来计算从 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/

相关文章:

c# - 递归创建列表中所有给定的树路径?

pythonic方式替换列表列表的内容?

python - 用python字符串的ascii序数列表

python - Pandas :从timedelta中提取小时

c++ - xcode 中的泄漏 c++ 列表

r - 通过一列合并两个列表之间的 data.frames

recursion - 带尾递归的慢字节码

Python 递归回溯变量

python - 在 matplotlib 中绘制 3d 数据

python - 格式化纯文本时,如何让 python-markdown 附加 "urlify"链接?