table = [0]*3
table[0] = 0
table[1] = 1
for i in range(2,6):
table[2] = table[1] + table[0]
table[0] = table[1]
table[1] = table[2]
print(table[2])
小弟是初學者
不能完全理解這個code
希望有高手能幫幫忙
1.An====A0| A1 | A2 | A3 |.... An
值====0 | 1 | 0+1 | (0+1)+1 | A(n-1)+A(n-2)
table[n] 等於第n項的值的話
一開始table[2] 為table[0] 加 table[1]
之後把table[0] 更新為table[1]的值
table[1] 更新為table[2]的值
新的table[2]等於 新的table[1]+table[0]
相當於舊的table[2]+table[1]
我這樣理解是對的嗎
但為甚麼第一行要寫成那樣阿
還有table是什麼意思
table = [0,1,1]
for i in range(2,11):
table[2] = table[1] + table[0]
table[0] = table[1]
table[1] = table[2]
print(table[2])
改成這樣也一樣
list乘法就是把list元素重複幾次而已,你的理解是沒錯的。
玩看看
#!/usr/local/bin/python3
x, y = 0, 1
print("# 1 = %5d" % y);
for i in range (2, 11):
fib = x + y
print("#%2d = %5d" % (i, fib))
x, y = y, fib
print('-' * 10)
fibs = [0, 1]
n = 10
for i in range(n-1):
fibs.append(fibs[-2] + fibs[-1])
fibs = fibs[1:]
print(fibs)
result:
| => ./fib1.py
# 1 = 1
# 2 = 1
# 3 = 2
# 4 = 3
# 5 = 5
# 6 = 8
# 7 = 13
# 8 = 21
# 9 = 34
#10 = 55
----------
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]