【问题标题】:Creating Python Factorial创建 Python 阶乘
【发布时间】:2013-10-01 03:59:51
【问题描述】:

晚上,

我是遇到麻烦的 Python 学生的介绍人。 我正在尝试制作一个 python 阶乘程序。它应该提示用户输入 n,然后计算 n 的阶乘,除非用户输入 -1。我被困住了,教授建议我们使用 while 循环。我知道我什至还没有遇到'if -1'的情况。不知道如何让 python 计算阶乘,而无需公然使用 math.factorial 函数。

import math

num = 1
n = int(input("Enter n: "))

while n >= 1:
     num *= n

print(num)

【问题讨论】:

  • 看来你快到了,我就一行一行地看。
  • 只需在 while 循环中尝试一些打印语句,看看发生了什么......

标签: python factorial


【解决方案1】:

学校里的“经典”阶乘函数是递归定义的:

def fact(n):
    rtr=1 if n<=1 else n*fact(n-1)
    return rtr

n = int(input("Enter n: "))
print fact(n)

如果你只是想要一种方法来解决你的问题:

num = 1
n = int(input("Enter n: "))

while n > 1:
    num *= n
    n-=1        # need to reduce the value of 'n' or the loop will not exit

print num

如果您想测试小于 1 的数字:

num = 1
n = int(input("Enter n: "))

n=1 if n<1 else n    # n will be 1 or more...
while n >= 1:
    num *= n
    n-=1        # need to reduce the value of 'n' or the loop will not exit

print num

或者,输入后测试n:

num = 1
while True:
    n = int(input("Enter n: "))
    if n>0: break

while n >= 1:
    num *= n
    n-=1        # need to reduce the value of 'n' or the loop will not exit

print num

这是一个使用reduce的函数式方法:

>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800

【讨论】:

  • 我们还没有介绍定义我们自己的函数。第二个代码块是它——我真的很接近但不完全在那里。如何再次在打印语句中引用我的变量?是否可以在 while 语句中添加输入 -1 的警告,或者我是否需要 if/then 语句? ` num = 1 n = int(input("Enter n: ")) while n > 1: num *= n n-=1 print ("n "的阶乘是" num) n = int(input("输入 n:")) `
  • 对不起,不知道如何在 cmets 中添加中断
  • 对不起,这是非常可怕的 python,尤其是。 n=1 if n&lt;1 else n 部分。
【解决方案2】:

其实你们很亲近。只需在每次迭代时更新 n 的值即可:

num = 1
n = int(input("Enter n: "))

while n >= 1:
    num *= n
    # Update n
    n -= 1
print(num)

【讨论】:

    【解决方案3】:

    我是 python 新手,这是我的阶乘程序。

    def 阶乘(n):

    x = []
    for i in range(n):
        x.append(n)
        n = n-1
    print(x)
    y = len(x)
    
    j = 0
    m = 1
    while j != y:
        m = m *(x[j])
        j = j+1
    print(m)
    

    阶乘(5)

    【讨论】:

      【解决方案4】:

      你可以这样做。

          def Factorial(y):
              x = len(y)
              number = 1
              for i in range(x):
                  number = number * (i + 1)
                  print(number)
      

      【讨论】:

        【解决方案5】:
        #Factorial using list
        fact=list()
        fact1=input("Enter Factorial Number:")
        for i in range(1,int(fact1)+1):
            fact.append(i)
         print(fact)
         sum=fact[0]
         for j in range(0,len(fact)):
                sum*=fact[j]
                print(sum)
        

        【讨论】:

        • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
        猜你喜欢
        • 1970-01-01
        • 2010-10-21
        • 1970-01-01
        • 1970-01-01
        • 2011-07-05
        • 2015-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多