【问题标题】:How to make python function start back over if conditions aren't met?如果不满足条件,如何让python函数重新开始?
【发布时间】: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


    【解决方案1】:

    您可以应用一些循环来实现这样的目标。首先,while 循环。 while 循环,您可能知道,一直运行直到满足条件。如果您有很多条件,while 语句可能会变得非常难看。如果条件很多,很多人会选择使用while True。使用break 将退出循环。

    def rand_string():
        while True:
            string = "".join(random.sample("abcdefghijk", 7))
            if string == "afedgcb":
                break
            elif string == "cdefgab":
                break
            elif string == "gbadcef":
                break
            else:
                continue
    
        return string
    

    在上面,我们从字符串 abcdefghijk 中选择 7 个随机字母,并检查这 7 个随机字母是 afedgcbcdefgab 还是 gbadcef。如果是这样,我们跳出循环并返回字符串。如果没有,我们将重新开始循环。 else/continue 不是必需的,如果没有满足任何条件,循环仍然会重新开始,因为我们没有跳出循环。

    另一种选择是递归。下面的示例只是从 0 和 10 中选择一个随机数并检查它是否等于 5。如果是,我们返回该数字。如果没有,我们只是再次运行该函数。

    def rand_num_recursion():
        num = random.randint(0,10)
        if num == 5:
            return num
        else:
            return rec()
    

    现在,如果你是print(rec()),答案总是5。为什么?因为函数会一直运行,直到选择的随机数为 5。这个递归函数也可以很容易地转换为 while 循环:

    def rand_num_while():
        num = random.randint(0,10)
        while num != 5:
            num = random.randint(0,10)
        return num
    

    如果有参数怎么办?

    使用递归可以轻松完成。当然,下面的例子只是为了演示目的——你永远不需要一个函数来“清空”一个列表,它只是一个如何将更新的参数传回循环开头的例子。

    def empty_list(lst):
        if len(lst) == 0:
            return lst
        else:
            print(lst)
            return empty_list(lst[:-1]) # return all members of the list except for the last one
    

    当你写print(empty_list([1,2,3,4,5,6]))并在函数中保留print(lst)时,输出如下:

    [1, 2, 3, 4, 5, 6]
    [1, 2, 3, 4, 5]
    [1, 2, 3, 4]
    [1, 2, 3]
    [1, 2]
    [1]
    []
    

    如您所见,每次不满足条件时,我们都会将更新后的参数传回循环的开头。在此示例中,您可以看到每次循环发生时,它都会从列表中删除最后一个元素并将其传递回开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多