【发布时间】:2021-02-23 01:19:33
【问题描述】:
我正在尝试创建一个函数,只要它们 == 1(而不是 0),就可以将谣言从一个像素传播到其他相邻像素。我认为我现在拥有的功能可以一次将其传播到相邻像素,但我希望它每次使用更新版本的像素图一次又一次地循环。当某些条件不满足时,如何让它循环回到顶部?
def spread_rumor(array):
new_array = np.zeros_like(array) #make a copy of your city
for i in range(array.shape[0]): #for each index i for the number of rows:
for j in range(array.shape[1]): #for each index j for the number of columns
if array[i,j] == 0:
new_array[i,j] = 0
elif array[i,j] == 2:
new_array[i,j] = 2
elif array[i,j] == 1: #if the value of the city/board at [i,j] is a 1:
new_array[i,j] = 1 #we only do something if we find a person who can learn the rumor
neighbors = getNeighborValues(i,j, array) #get all of the values of their neighborhood cells
if np.any(np.array(neighbors) == 2) == True:
new_array[i,j] = 2
## there is more than one way to do this!
## You could use a loop to check all the neighbors and move one once you find one
## or you could check to see if there is a 2 in any of the neighbors
frac_empty = np.count_nonzero(array == 0)/array.size
frac_house = np.count_nonzero(array == 1)/array.size
frac_rumor = np.count_nonzero(array == 2)/array.size
if frac_empty + frac_rumor == 1.0: #the copy of our city is the same as city:
##our simulation isn't changing anymore,
##so making a copy and updating it isn't going to
##lead to further changes
spread_rumor = False
else:
##there are still changes going on
#this is where I would want it to start back over at the top again
return showCity(new_array) #this function creates a plt.imshow representation of the resulting array
【问题讨论】:
标签: python arrays function loops