无法在Python中创建阶乘函数

发布于 2024-07-24 23:23:40 字数 405 浏览 9 评论 0原文

我的代码

import sys

number=int(sys.argv[1])

if number == 0
    fact=1
else
    fact=number
for (x=1; x<number; x++)
    fact*=x;             // mistake probably here

print fact

我收到错误

File "factorial.py", line 5
    if number == 0
                 ^
SyntaxError: invalid syntax

如何在Python中创建阶乘函数?

My code

import sys

number=int(sys.argv[1])

if number == 0
    fact=1
else
    fact=number
for (x=1; x<number; x++)
    fact*=x;             // mistake probably here

print fact

I get the error

File "factorial.py", line 5
    if number == 0
                 ^
SyntaxError: invalid syntax

How can you make a factorial function in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦萦几度 2024-07-31 23:23:41

实际上,最简单的选择是:

def factorial(n):
    x = n
    for j in range(1, n):
        x = j*x
    return x

是的,不知何故,它有效。

你怎么想不到这一点? 我不知道。

一个 for 循环和一个乘法器,真正简单是最好的方法,对吗?

编辑:哦,等等,我们正在以最高效的 cpu 效率工作? 哦哦......

really, the simplest option would be:

def factorial(n):
    x = n
    for j in range(1, n):
        x = j*x
    return x

yes, somehow, it works.

How could you not think of this? I don't know.

A for loop and a multiplier, really simplicity is the best way to go, right?

EDIT: Oh, wait, we're working for the most cpu-efficeint way? ohhhh.....

旧情勿念 2024-07-31 23:23:41

我的猜测,这可能是有帮助

def recursive_fact(x :int)->int:
    if x == 0:
        yield 1
    yield x * next(recursive_fact(x-1))

和结果

print(list(recursive_fact(6)))

My guess, it may be helps

def recursive_fact(x :int)->int:
    if x == 0:
        yield 1
    yield x * next(recursive_fact(x-1))

and result

print(list(recursive_fact(6)))
酒绊 2024-07-31 23:23:40

错误所在的行应为“

if number == 0:

注意末尾的冒号”。

此外,您需要在 else 和 for 之后添加相同的冒号。 冒号的工作方式与其他语言中的 {} 类似。

最后,这不是 Python 中 for 循环的工作方式。 您想要使用该列表的代码将与

for x in range(1,number):

如果您将其放入 C 风格语言中,

您编写的代码具有相同的效果。 编辑:哎呀,我给出的 for 循环是错误的,它会包含 0。我更新了代码来纠正这个问题。

The line that your error is on should read

if number == 0:

Note the colon on the end.

Additionally, you would need to add the same colon after the else and the for. The colons work similarly to {} in other languages.

Finally, thats not how for loops work in Python. The code you want to use that list would be

for x in range(1,number):

Which would have the same effect of what you wrote, if you put that in a C style language.

EDIT: Oops, the for loop I gave was wrong, it would have included 0. I updated the code to correct this.

跨年 2024-07-31 23:23:40

我知道您可能出于教育原因尝试自己实现这一点。

但是,如果没有,我建议使用 math 模块内置阶乘函数(注意:需要 python 2.6 或更高版本):

>>> import math
>>> math.factorial(5)
120

该模块是用 C 编写的,因此,它会非常多比用 python 编写要快。 (不过,如果您不计算大阶乘,那么无论如何它都不会太慢)。

I understand that you are probably trying to implement this yourself for educational reasons.

However, if not, I recommend using the math modules built-in factorial function (note: requires python 2.6 or higher):

>>> import math
>>> math.factorial(5)
120

This module is written in C, and as such, it'll be much much faster than writing it in python. (although, if you aren't computing large factorials, it won't really be too slow either way).

如此安好 2024-07-31 23:23:40

这是您的代码,已修复并正在运行:(

import sys
number = int(sys.argv[1])
fact = 1
for x in range(1, number+1):
    fact *= x

print fact

阶乘零是一,对于任何不知道的人 - 我必须查找它。8-)

您需要在 ifelse 之后使用冒号for 等,并且 for 在 Python 中的工作方式与 C 不同。

Here's your code, fixed up and working:

import sys
number = int(sys.argv[1])
fact = 1
for x in range(1, number+1):
    fact *= x

print fact

(Factorial zero is one, for anyone who didn't know - I had to look it up. 8-)

You need colons after if, else, for, etc., and the way for works in Python is different from C.

我乃一代侩神 2024-07-31 23:23:40

Mark Rushakoff 的fact(n) 函数效率如此之高的原因是他错过了reduce() 函数。 因此它实际上从未进行过计算。

更正后的内容是(我得到了):

import operator, timeit, math
#
def fact1(n):  return reduce(lambda x,y: x*y,  range(1,n+1),1)
def fact1x(n): return reduce(lambda x,y: x*y, xrange(1,n+1),1)
def fact2(n):  return reduce(operator.mul   ,  range(1,n+1),1)
def fact2x(n): return reduce(operator.mul   , xrange(1,n+1),1)
#
def factorialtimer():
    for myfunc in [ "fact1", "fact1x", "fact2", "fact2x" ]:
        mytimer = timeit.Timer(myfunc+"(1500)", "from __main__ import "+myfunc)
        print("{0:15} : {1:2.6f}".format(myfunc, mytimer.timeit(number=1000)))

    mytimer = timeit.Timer("factorial(1500)", "from math import factorial")
    print("{0:15} : {1:2.6f}".format("math.factorial", mytimer.timeit(number=1000)))

结果输出为 1500!,1000x:

fact1           : 3.537624
fact1x          : 4.448408
fact2           : 4.390820
fact2x          : 4.333070
math.factorial  : 4.091470

是的,我已经检查过它们都产生相同的值!
我不明白为什么 lambda xrange 比 lambda range 差这么多。 嗯。
版本:
Win32 上的 PythonWin 2.6.2(r262:71605,2009 年 4 月 14 日,22:40:02)[MSC v.1500 32 位(Intel)]。

嗯......重新运行它我得到了一些更可信的东西

fact1           : 7.771696
fact1x          : 7.799568
fact2           : 7.056820
fact2x          : 7.247851
math.factorial  : 6.875827

在Python 2.6.5上(r265:79063,2010年6月12日,17:07:01)[GCC 4.3.4 20090804(发布)1]在cygwin上:

fact1           : 6.547000
fact1x          : 6.411000
fact2           : 6.068000
fact2x          : 6.246000
math.factorial  : 6.276000

全部真的是在噪音中,不是吗?

The reason Mark Rushakoff's fact(n) function was so much more efficient was that he missed-off the reduce() function. Thus it never actually did the calculation.

Corrected it reads (and I get):

import operator, timeit, math
#
def fact1(n):  return reduce(lambda x,y: x*y,  range(1,n+1),1)
def fact1x(n): return reduce(lambda x,y: x*y, xrange(1,n+1),1)
def fact2(n):  return reduce(operator.mul   ,  range(1,n+1),1)
def fact2x(n): return reduce(operator.mul   , xrange(1,n+1),1)
#
def factorialtimer():
    for myfunc in [ "fact1", "fact1x", "fact2", "fact2x" ]:
        mytimer = timeit.Timer(myfunc+"(1500)", "from __main__ import "+myfunc)
        print("{0:15} : {1:2.6f}".format(myfunc, mytimer.timeit(number=1000)))

    mytimer = timeit.Timer("factorial(1500)", "from math import factorial")
    print("{0:15} : {1:2.6f}".format("math.factorial", mytimer.timeit(number=1000)))

Resulting output for 1500!, 1000x:

fact1           : 3.537624
fact1x          : 4.448408
fact2           : 4.390820
fact2x          : 4.333070
math.factorial  : 4.091470

And yes, I have checked they all yield the same value!
I Can't understand why the lambda xrange is so much worse than the lambda range. Hmmm.
Version:
PythonWin 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32.

Hmm... on re-running it I get something more believable

fact1           : 7.771696
fact1x          : 7.799568
fact2           : 7.056820
fact2x          : 7.247851
math.factorial  : 6.875827

And on Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) [GCC 4.3.4 20090804 (release) 1] on cygwin:

fact1           : 6.547000
fact1x          : 6.411000
fact2           : 6.068000
fact2x          : 6.246000
math.factorial  : 6.276000

All in the noise really, isn't it?

小镇女孩 2024-07-31 23:23:40

这是一个函数阶乘,您几乎要求它:

>>> def fact(n): return reduce (lambda x,y: x*y, range(1,n+1))
... 
>>> fact(5)
120

它不适用于fact(0),但您可以担心 fact 范围之外的问题:)


Masi 询问函数样式是否是比 Richie 的实施更有效率。 根据我的快速基准测试(令我惊讶的是!),是的,我的速度更快。 但我们可以做一些改变。

首先,我们可以按照另一条评论中的建议用 operator.mul 替换 lambda x,y: x*y 。 Python 的 lambda 运算符带来了不小的开销。 其次,我们可以用 xrange 替换 rangexrange 应该在线性空间中工作,根据需要返回数字,而 range 一次创建整个列表。 (然后请注意,对于过大的数字范围,您几乎肯定必须使用 xrange

因此新定义变为:

>>> import operator
>>> def fact2(n): return reduce(operator.mul, xrange(1,n+1))
... 
>>> fact2(5)
120

令我惊讶的是,这实际上导致性能下降。 这是 Q&D 基准:

>>> def fact(n): return (lambda x,y: x*y, range(1,n+1))
... 
>>> t1 = Timer("fact(500)", "from __main__ import fact")
>>> print t1.timeit(number = 500)
0.00656795501709

>>> def fact2(n): return reduce(operator.mul, xrange(1,n+1))
...
>>> t2 = Timer("fact2(500)", "from __main__ import fact2")
>>> print t2.timeit(number = 500)
0.35856294632

>>> def fact3(n): return reduce(operator.mul, range(1,n+1))
... 
>>> t3 = Timer("fact3(500)", "from __main__ import fact3")
>>> print t3.timeit(number = 500)
0.354646205902

>>> def fact4(n): return reduce(lambda x,y: x*y, xrange(1,n+1))
... 
>>> t4 = Timer("fact4(500)", "from __main__ import fact4")
>>> print t4.timeit(number = 500)
0.479015111923

>>> def fact5(n):
...     x = 1
...     for i in range(1, n+1):
...             x *= i
...     return x
... 
>>> t5 = Timer("fact5(500)", "from __main__ import fact5")
>>> print t5.timeit(number = 500)
0.388549804688

这是我的 Python 版本,以防有人想要交叉检查我的结果:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2

Here's a functional factorial, which you almost asked for:

>>> def fact(n): return reduce (lambda x,y: x*y, range(1,n+1))
... 
>>> fact(5)
120

It doesn't work for fact(0), but you can worry about that outside the scope of fact :)


Masi has asked whether the functional style is more efficient than Richie's implementation. According to my quick benchmark (and to my surprise!) yes, mine is faster. But there's a couple things we can do to change.

First, we can substitute lambda x,y: x*y with operator.mul as suggested in another comment. Python's lambda operator comes with a not-insignificant overhead. Second, we can substitute xrange for range. xrange should work in linear space, returning numbers as necessary, while range creates the whole list all at once. (Note then, that you almost certainly must use xrange for an excessively large range of numbers)

So the new definition becomes:

>>> import operator
>>> def fact2(n): return reduce(operator.mul, xrange(1,n+1))
... 
>>> fact2(5)
120

To my surprise, this actually resulted in slower performance. Here's the Q&D benchmarks:

>>> def fact(n): return (lambda x,y: x*y, range(1,n+1))
... 
>>> t1 = Timer("fact(500)", "from __main__ import fact")
>>> print t1.timeit(number = 500)
0.00656795501709

>>> def fact2(n): return reduce(operator.mul, xrange(1,n+1))
...
>>> t2 = Timer("fact2(500)", "from __main__ import fact2")
>>> print t2.timeit(number = 500)
0.35856294632

>>> def fact3(n): return reduce(operator.mul, range(1,n+1))
... 
>>> t3 = Timer("fact3(500)", "from __main__ import fact3")
>>> print t3.timeit(number = 500)
0.354646205902

>>> def fact4(n): return reduce(lambda x,y: x*y, xrange(1,n+1))
... 
>>> t4 = Timer("fact4(500)", "from __main__ import fact4")
>>> print t4.timeit(number = 500)
0.479015111923

>>> def fact5(n):
...     x = 1
...     for i in range(1, n+1):
...             x *= i
...     return x
... 
>>> t5 = Timer("fact5(500)", "from __main__ import fact5")
>>> print t5.timeit(number = 500)
0.388549804688

Here's my Python version in case anyone wants to cross-check my results:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文