簡體   English   中英

創建斐波那契數列生成器(初學者 Python)

[英]Creating fibonacci sequence generator (Beginner Python)

嗨,我正在嘗試用 Python 創建一個斐波那契數列生成器。 這是我的代碼:

d =raw_input("How many numbers would you like to display")

a = 1
b = 1

print a
print b

for d in range(d):
    c = a + b 
    print c
    a = b
    b = c

當我運行這個程序時,我收到錯誤:

File "Fibonacci Sequence Gen.py", line 10, in <module>
    for d in range(d):
TypeError: range() integer end argument expected, got str

感謝您的幫助,我正在嘗試通過基本項目自學 Python。

raw_input 返回一個字符串。 因此,將 d 轉換為整數:

d = int(d)

還有一件事:不要for d in range(d)使用for d in range(d) 它有效,但它很糟糕,非pythonic,無論如何。
試試這種方式,例如:

numbers = raw_input("How many numbers would you like to display")

a = 1
b = 1

print a
print b

for d in range(int(numbers)):
    c = a + b 
    print c
    a = b
    b = c

編輯:我在答案下方完成了額外的代碼調整(感謝評論者):

# one space will separate better visually question and entry in console
numbers = raw_input("How many numbers would you like to display > ")    

# I personnally prefer this here, although you could put it
# as above as `range(int(numbers))` or in `int(raw_input())`
# In a robust program you should use try/except to catch wrong entries
# Note the number you enter should be > 2: you print 0,1 by default
numbers = int(numbers)  

a, b = 0, 1        # tuple assignation
                   # note fibonnaci is 0,1,1,2,3...

print a            # you can write this as print "%i\n%i" % (a, b)
print b            # but I think several prints look better in this particular case.

for d in range(numbers - 2):  # you already printed 2 numbers, now print 2 less
    c = a + b 
    print c
    a, b = b, c    # value swapping.
                   # A sorter alternative for this three lines would be:
                   # `a, b = b, a + b`
                   # `print b` 

問題

這里的問題是:

d = raw_input("How many numbers would you like to display")

您將輸入中的字符串分配給d變量,然后將其傳遞給range() 但是range()期望整數,而不是字符串,並且 Python 不會自動轉換它(它將轉換留給您)。

解決方案

解決方案是將raw_input()結果轉換為int ,如下所示:

d = int(raw_input("How many numbers would you like to display"))

除非您提供非整數,否則一切都會正常。

但是有更好的(更短、更高效、更封裝)的生成斐波那契數的方法(見下文)。

生成斐波那契數的更好方法

我相信這是最好的(或幾乎是最好的)解決方案:

def fibo(n):
    a, b = 0, 1
    for i in xrange(n):
        yield a
        a, b = b, a + b

這是一個生成器,而不是一個簡單的函數。 它非常高效,它的代碼很短並且不打印任何東西,但是你可以像這樣打印它的結果:

>>> for i in fibo(20):
    print i,


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

或將其轉換為這樣的列表:

>>> list(fibo(20))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

在您的情況下應用上述內容

將上述內容應用於您的代碼后,它可能如下所示:

def fibo(n):
    a, b = 0, 1
    for i in xrange(n):
        yield a
        a, b = b, a + b

d = int(raw_input("How many numbers would you like to display"))
for i in fibo(d):
    print i

它回答你的問題嗎?

您必須將輸入轉換為數字,如下所示:

d = int(raw_input("How many numbers would you like to display: "))

此外,為了好玩,斐波那契數列可以更簡潔地表達:

a, b = 0, 1
for i in range(d):
    print a
    a, b = b, a+b

raw_input返回字符串類型。您需要將其轉換為int

>>> x = raw_input()
2
>>> x
'2'
>>> type(x)
<type 'str'>

range函數需要int作為參數而不是string

這就是為什么當我這樣做時

>>> range(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got str.

所以,把它改成

for x in range(int(d)):

更簡單的方法:

a = [0,1]
for n in range(1,41):
  a.append(a[n]+a[n-1])
  print a[-1]

1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141

我看到很多過於復雜的斐波那契數列程序,所以我只是用一個 while 循環來做這個; 在 while 循環后更改數字

a = 0 b = 1 while a <= 1000000000: #Changing this number will change how long the sequence goes on for print(a) print(b) a = a+bb = b+a我知道這不是你的程序但它是一個非常基本的版本; 我希望這有幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM