【问题标题】:Python : printing lines of factorial "*" through recursionPython:通过递归打印阶乘“*”行
【发布时间】: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


【解决方案1】:

您编写的函数返回一个列表,其中包含哪一行应该有多少个“*”。

对于n = 3,它返回:[1, 2, 6]

所以要打印它们:

for x in output:
    print('*'*x) # print * x times

【讨论】:

    【解决方案2】:

    我同意@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 的阶乘!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多