我试图找出这些临时变量的含义

时间:2016-08-02 05:44:43

标签: python

def genfibon(n):      #fib sequence until n
   a=1
   b=1
   for i in range n:
      yield a
      t=a
      a=b
      b=t+b        

有人可以解释t变量吗?看似t=a,然后是a=b,然后是b=t,因为a=ba=tb=t+b怎么办?

4 个答案:

答案 0 :(得分:4)

假设a = 2且b = 3.

t = a # now t = 2
a = b # now a = 3, but t is unchanged
b = t + b # now b = 5

关键是第二部分。 t = a表示ta的值相同。这并不意味着ta现在都是一样的。

您可以在Python提示符下尝试:

a = 3
b = a
a = 5
print(b) # still 3

答案 1 :(得分:2)

它称为交换变量。你如何替换变量的值?

正如@smarx所说,当a = 2b = 3时,你如何做到a = 3b = 2

当你执行a = 3时,a(2)的旧值会丢失,因此您不知道要将b设置为什么。所以我们将它存储在临时变量(t)中。

所以,

t = a //(saves 2 in t)
a = b //(now both a and b have same values)
b = t //(b gets the old value of a)
// now a = old value of b 
// and b = old value of a.
瞧,变量是互换的。

嗯,这需要交换。这只是部分用于此代码。最后一个语句b = t + b代码正在做什么,用a添加a的旧值(而不是替换它)。为什么?你可以通过添加前面的2来获得斐波那契序列中的下一个数字。

2,3,5是斐波那契序列,因为5 = 2 + 3(给定2和3是种子值)。这正是这段代码的作用。

答案 2 :(得分:2)

在你的第一次跑步中

yield a # will return 1 
t = a  # which is 1
a = b  # which is 1
b = t + b  # which is 2 as t = 1 and b = 1 

在你的第二轮

yield a # will return 1 
t = a  # which is 1
a = b  # which is 2
b = t + b  # which is 3 as t = 1 and b = 2

在你的第3次运行中

yield a # will return 2 
t = a  # which is 2
a = b  # which is 3
b = t + b  # which is 5 as t = 2 and b = 3   

在第4轮

yield a # will return 3 
t = a  # which is 3
a = b  # which is 5
b = t + b  # which is 8 as t = 3 and b = 5

等等......

答案 3 :(得分:1)

让我们逐句发言。

  1. t=a表示a的值已存储在t
  2. a=b表示b的值存储在a中。 (因此a现在包含系列中的下一个元素)
  3. b=t+b表示b的值现在为t + b,这意味着a+b,因为t现在包含a的值(根据第一个)工序)。