[英]Fibonacci sequence python
我正在嘗試了解 Python,但我仍然不明白。 我是這門語言的新手,想正確理解它。 這是使用循環的斐波那契數列中的一條線。 請解釋這段代碼的含義。 我正在嘗試手動獲取模式。 我得到了最多 3 個模式,但是在 3 個之后我沒有得到答案。
a, b = 0, 1
while b < 50:
print(b)
a, b = b, a + b
a, b = b, a + b
這稱為多重分配。 它基本上是一個原子版本:
a = b
b = a + b
通過原子,我的意思是右邊的所有內容都是在將其調入左邊的變量之前計算出來的。 所以a
變成了b
並且b
變成了a
加b
的舊版本,相當於非原子的:
old_a = a
a = b
b = old_a + b
所以,就你所看到的而言:
a b output
================ ========================= ======
(initial values) (initial values)
0 1 1
(becomes prev b) (becomes sum of prev a,b)
1 1 1
1 2 2
2 3 3
3 5 5
5 8 8
這確切的代碼(有多種布局的解釋和說明),可以發現這里的教程。
這是多重分配(或元組解包)。
根據Python 教程:
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print(b)
... a, b = b, a+b
...
1
1
2
3
5
8
此示例介紹了幾個新功能。
第一行包含一個多重賦值:變量 a 和 b 同時獲得新值 0 和 1。在最后一行再次使用它,證明右側的表達式在任何賦值之前都首先被評估發生。 右邊的表達式是從左到右計算的。
多個答案怎么樣?
def fib(num):
a = 0
b = 1
while b <= num:
prev_a = a
a = b
b = prev_a +b
#print b
return a
print fib(13)
def pythonic_fib(num):
a,b = 0,1
while b <= num:
a,b = b, a+b
return a
print pythonic_fib(13)
def recursive_fib(num, a, b):
if (b >= num):
return b
else:
return recursive_fib(num, b, a+b)
print recursive_fib(13, 0, 1)
我知道這是一個老問題,但只是想我已經用了 2 美分,因為其中很多對於斐波那契數列(在給定答案之外)來說似乎有點過於復雜,以防有人仍在尋找。 你可以這樣做:
a=1
b=0
while b<400:
a=a+b
b=a+b
print(a)
print(b)
這將提供所需的序列輸出(對於您設置的 b 小於)。
#The easy way to generate Fibonacci series in python is
user = input('Please enter the integer range for Fibonacci series: '); # take input from user form the range of Fibonacci series.
try:# to ignore wrong inputs and be aware from error we use try and except block
d=int(user);# converts the user input to type integer.
a=0; #initialization``
b=1; #initialization
print(a,b,end=' '); # print initial value of a and b
for c in range(0,d): # here c is iterable variable and in range o is the starting point and d is the ending range which we get from user
c=a+b;
a=b;
b=c;
print(c,end=' ');
except Exception as e:
print(e); # if any error occurred in the input here it shows which error occurs
a= int(input("Enter the first number:"));
Enter the first number:0
b= int(input("enter the second number:"));
enter the second number:1
n= int (input("enter the number of terms:"));
enter the number of terms:10
print(a,b);
0 1
while(n>2):
c=a+b;
a=b;
b=c;
print(c);
n=n-1;
1
2
3
5
8
13
21
34
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.