我的python阶乘代码有什么问题

您所在的位置:网站首页 求阶乘python代码 我的python阶乘代码有什么问题

我的python阶乘代码有什么问题

2023-06-27 18:58| 来源: 网络整理| 查看: 265

百度翻译此文   有道翻译此文 问题描述

I have the following code for calculating the factorial of a number in python. but I couldnt understand why I am getting the answer as 1. can some one correct my code. I want to calculate the factorial without using recursion.

def factorial (n): result =1 num = n while n 1: 其他推荐答案

Others pointed out what's wrong with your code, but I wanted to point out that a factorial function really lends itself to a more functional (as in: functional programming) solution; this avoids the issue with getting the condition for the while loop altogether because you don't have any loop at all. The insight is that the factorial of n is the product of 1..n, and the product can be defind very easily using Python's reduce function. To avoid losing performance out of sight, here's what my Python 2.7 interpreter gives for your (fixed) code:

python -m timeit -s "import original" "original.factorial(10)" 1000000 loops, best of 3: 1.22 usec per loop

A shorter version (a one-liner) which is more declarative is possible:

def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1))

...alas, it's slower:

python -m timeit -s "import func1" "func1.factorial(10)" 1000000 loops, best of 3: 1.98 usec per loop

However, this can be solved by using xrange instead of range and operator.mul instead of a custom lambda:

import operator def factorial(n): return reduce(operator.mul, xrange(1, n+1))

And for me, this is even faster than the original code:

python -m timeit -s "import func2" "func2.factorial(10)" 1000000 loops, best of 3: 1.14 usec per loop

Personally, I'd factor out the reduce call to make the code even clearer (at the expense of a tiny little bit of performance):

import operator def product(it): return reduce(operator.mul, it) def factorial(n): return product(xrange(1, n+1))

I like this version for being fast, and for being explicit: the factorial is defined to be the product of the range [1..n+1[ (i.e. n+1 is excluded). The performance difference becomes more apparent if you try to compute the factorial of larger numbers:

python -m timeit -s "import original" "original.factorial(30)" 100000 loops, best of 3: 5.25 usec per loop

vs.

python -m timeit -s "import func3" "func3.factorial(30)" 100000 loops, best of 3: 3.96 usec per loop 其他推荐答案

while 5 < 1 is always false, so result = 1 is returned. That's wrong.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3