为for循环编码变量n(i)=( - 1,-1,1,1,-1,-1,1,1,...)

时间:2014-09-23 11:53:11

标签: python python-3.x tkinter

我正在尝试为Fibronacci数字的用户输入值创建切片。我的下面有什么作品,但似乎粗糙。

from tkinter import *
def main():
    print("This program graphically represent the Fibronacci numbers up to")
    print("the nth number requested by the user (1,1,2,3,5,8,...)")
    n = eval(input("Enter the number of the series you would like -eg n=7 for 13:"))
    a,b=1,1
    x0,y0=150,150
    canvas = Canvas(width=300, height=300, bg='white')
    canvas.pack(expand=YES, fill=BOTH)        
    print(a)
    print(b)
    m1=[1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1]
    m2=[-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1]
    color=["red", "blue", "green","yellow","magenta",
           "red", "blue", "green","yellow","magenta",
           "red", "blue", "green","yellow","magenta",
           "red", "blue", "green","yellow","magenta",
           "red", "blue", "green","yellow","magenta"]
    for i in range (1, n-1):

            a,b=b,a+b
            print(b)

            #m1=(-1)**i
            #m2=(-1)**(i+1)

            x1,y1=x0+m1[i-1]*b*10,y0+m2[i-1]*b*10

            canvas.create_rectangle(x0,y0,x1,y1,dash=(4, 4),fill=color[i-1]) 
            print(x0,y0)
            print(x1,y1)

            x0,y0=x1,y1
            print(x0,y0)
    print("The ",n,"th Fibronacci number is ", b,)   
main()

如何在for循环中创建列表m1和m2?

2 个答案:

答案 0 :(得分:1)

您可以定义自己的迭代器,如下所示:

$ cat t.py 
class Alternator:
    def __init__(self, first=1):
        self.previous = first
        self.current = 1

    def __iter__(self):
        return self

    def next(self): # Python 3: def __next__(self):
        self.previous, self.current = self.current, -self.previous
        return self.current

然后,像这样使用它

m1 = Alternator(first=-1)
m2 = Alternator(first=1)
for i in range(20):
    print "m1=%d\tm2=%d" % (m1.next(),  m2.next())

,结果是m1m2获取您在示例中的列表中设置的序列中的值:

$ python t.py 
m1=1    m2=-1
m1=-1   m2=-1
m1=-1   m2=1
m1=1    m2=1
m1=1    m2=-1
m1=-1   m2=-1
m1=-1   m2=1
m1=1    m2=1
m1=1    m2=-1
m1=-1   m2=-1
m1=-1   m2=1
m1=1    m2=1
m1=1    m2=-1
m1=-1   m2=-1
m1=-1   m2=1
m1=1    m2=1
m1=1    m2=-1
m1=-1   m2=-1
m1=-1   m2=1
m1=1    m2=1

答案 1 :(得分:0)

不是存储m1m2color的预先计算的值列表,而是定义迭代器。

import itertools import izip, cycle, is lice


m1s = cycle([1, 1, -1, -1])  # We don't want the first 1 ...
m1s = islice(m1s, 1, None)   # ... so we'll skip it. Think m1s = m1s[1:]
m2s = cycle([-1, -1, 1, 1])
colors = cycle(["red", "blue", "green","yellow","magenta"])

for m1, m2, color in izip(m1s, m2s, colors):
    # ...

cycle创建一个迭代器,从输入中一次返回一个元素,根据需要重复列表。我们使用islice在第二个元素上启动m1s,跳过m1s中的第一个元素。 izip返回元组的迭代器,因此第一个元素是由三个迭代器中的第一个项组成的元组,第二个元素是第二个项,等等。

这样,您就不需要存储您需要的所有值的列表。