【问题标题】:converting to a for or while loop转换为 for 或 while 循环
【发布时间】:2015-04-19 07:51:12
【问题描述】:

我试图通过将其创建为 for 或 while 循环来转换此函数,但遇到了麻烦。

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

这是我尝试的:

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

【问题讨论】:

标签: python loops


【解决方案1】:

将上述递归程序转换为使用循环并不像将if 更改为while 那样简单。

def fact(n):
    result = 1
    while n >= 1:
        result = result * n
        n = n - 1
    return result

【讨论】:

    【解决方案2】:

    如果你使用循环,你不应该递归,你应该在循环内乘法。

    def fact(n):
        result = 1
        while n > 1:
            result *= n
            n = n - 1
        return result
    

    【讨论】:

    • python 中没有递减运算符 (--)。将其更改为 n -= 1
    • 可以在 Python 中的 while 循环上有一个 else:!它用的不多,只有当你有break时才有用。
    • 可以while 块上使用else 子句,但这里不需要。请参阅 Python 文档中的 The while statement
    【解决方案3】:

    使用for循环:

    result = 1
    for v in xrange(1, n + 1):
        result *= v
    return result
    

    使用理解:

    from operator import mul
    return reduce(mul, xrange(1, n + 1), 1)
    

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2014-12-18
      • 2017-04-26
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      相关资源
      最近更新 更多