繁体   English   中英

Python:通过递归打印阶乘“ *”的行

[英]Python : printing lines of factorial “*” through recursion

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

我同意@Anonta的打印解决方案(+1),但是如果您的唯一目标是打印星星,而不是将阶乘收集到列表中,则可以将打印内容合并到代码中并简化所有操作:

def factorialN(n):
    if n != 1:
        n *= factorialN(n - 1)

    print(n * '*')

    return n

number = int(input("Enter positive integer: "))

factorialN(number)

用法

Enter positive integer: 4
*
**
******
************************

此外,作为奖励, factorialN(n)返回的阶乘n作为一个数字!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM