康威的生活:在Python中迭代一个封闭的宇宙

时间:2009-12-08 15:31:53

标签: python

我刚刚开始学习Python,我正在尝试为康威的生命游戏编写一个程序。我正在尝试创建一个具有边界条件的封闭宇宙(这是相反的一侧/角落)。我想我已经这样做了,但是当它运行时我没有迭代循环,并且无法解决如何执行此操作。非常感谢提前!

def iterate_conway_closed(universe_t0, n_iter=1, display=False):
# This function is similar to your iterate_conway_open function
# but instead of adding a zero guard ring it should add a 
# ‘wrapping ring’ as explained earlier.  Use the same apply_rules
# function as part 1) to actually apply the rules once you have
# padded the universe.  
# Note that unlike the always 0 guard ring for an open universe
# the wrapping ring will need updating after every call to
# apply rules to reflect changes in the universe

height, width=universe_t0.shape
universe_array=numpy.zeros((height+2, width+2), dtype=numpy.uint8)
universe_array[1:-1, 1:-1]=universe_t0

def count(n_iter):
    n=0
    while n<= n_iter:
        yield n
        n+=1

for n in range(0,n_iter):
    universe_array[:1,1:-1]=universe_t0[-1:,:] # Maps the bottom row
    universe_array[0,1:-1]=universe_t0[-1:,0:]# Maps the top row
    universe_array[1:-1,0]=universe_t0[:,0]# Maps the left column
    universe_array[1:-1,-1]=universe_t0[:,-1]# Maps the right column
    universe_array[0,0]=universe_t0[-1,0]# Maps the bottom left corner
    universe_array[0,-1]=universe_t0[-1,-1]# Maps the bottom right corner
    universe_array[-1,0]=universe_t0[0,0]# Maps the top left corner
    universe_array[-1,-1]=universe_t0[0,-1]# Maps the top right corner      

for i in range(0, n_iter):
    universe_array=apply_rules(universe_array)


if display==True:
    b_print(universe_array)

return universe_array[1:-1, 1:-1]

2 个答案:

答案 0 :(得分:1)

您的问题可能是break声明

编辑:此外,你可能只想要一个循环,首先你初始化universe_array n_iter次,在第一次之后什么都不做。然后你应用规则n_iter次,你很可能想把它们放在同一个循环中,以便在每次迭代后宇宙得到正确的更新。

答案 1 :(得分:0)

据我所知你想创建一个迭代器函数。您需要做的是将return替换为yield

例如,如果你想创建一个迭代器函数,它将范围从0返回到x,请执行以下操作:

 def count(x=0):
     n = 0
     while n <= x:
         yield n
         n += 1

然后你可以用for语句迭代它:

for i in count(10):
    print(i)

# prints 0,1,2,3,4,5,6,7,8,9,10 (instead of "," there are line breaks)

break也是问题,因为当while循环遍历时,它将始终执行。