[英]Checking efficiency of a Python Fibonacci Sequence Generator?
我是python和编程新手。 我想知道这是否是为初学者生成斐波那契数的非常低效的方法?
a = 1
b = 1
total = 0
counter = input("Please enter the term you wish to end at: ")
print "1"
print""
print "1"
number = 2
while counter > number:
total = a+b
print ""
print total
a = b
b = total
number = number + 1
如果是这样,有人可以指出一些事情,例如:
研究什么/谷歌使我的代码更高效。
建议我需要进行的编程实践(我知道这不是我工作的巨大样本)。
使用python,尽管您仍想实现最短的Big Oh运行时间,但您不想像在C语言中那样担心效率。 您撰写本文的方式几乎可以达到最高的效率,因此您不必担心太多。 但是,使用while
来添加到计数器中并不是很pythonic。
可以这样写:
a, b = 0, 1
counter = input("Please enter the term you wish to end at: ")
for _ in xrange(counter): #xrange is more efficient than range, the number is not used so _ is used to show that
a, b = b, a+b
print a
print
您也可以为此使用生成器,这可能是您可以从事的编程实践...
def fib(end):
a, b = 0, 1
for _ in xrange(end):
a, b = b, a+b
yield str(a)
counter = input("Please enter the term you wish to end at: ")
print '\n\n'.join(fib(counter))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.