首页 > 解决方案 > 检查是否可以在 Python 中使用递归来均衡整数数组

问题描述

给定一个integer array大小为 5 且具有任意正值的 和m,我的任务是创建一个程序,该程序将检查是否可以使用以下过程来均衡这个数组(所有整数都相等):

作为m当前位置,它将跳转到另一个整数,并且通过跳转,该位置的整数会根据距该整数位置的距离而减小m

Example: [2, 2, 4, 2, 2] with m = 0 (first position)
          
we jump to  the third position to equalize the integer array, that means 4 minus (distance from current position to 4)
   
   v (m = 0)
  [2, 2, 4, 2, 2]

          v jump to index 2 (3rd position)
  [2, 2, (4 - abs(2-0)), 2, 2]

= [2, 2, 2, 2, 2] (all integer is equal)

since there is a way to equalize the array, return True.

数组中的整数只能是正数。如果无法均衡数组,则返回False

我设法制作了一个代码,但它不适用于隐藏案例(这是我们学校的问题)。

def canEqual(array, m):

    if min(array) == max(array): return True     # Array can be Equalized, Return True

    for integer in array:   
        if integer < 1: return False             # If there is an integer in the array
                                                 # less than 1, then return False since
                                                 # it cannot be.

    for index, integer in enumerate(array):           # Treats the min value in the array as the
        if integer > min(array) and index != m:       # basis for equalizing. If an element is greater
            temp = array[:]                           # than the minimum, the program will jump to this position
            temp[index] = integer-abs(m-index)        # and the cycle continues until either the array
                                                      # is equalized or there exists a non positive integer.

            if canEqual(temp, index): return canEqual(temp, index)   

我不确定我解决这个问题的方法是否正确。

标签: pythonarraysrecursionsearchinteger

解决方案


看一下(并尝试通过调查更好地理解它),取消注释这两个打印以更好地理解该过程,如果某些事情对您没有意义,请要求澄清。

def canEqual(cur_arr, m):
    if min(cur_arr) < 0:
        return False
    if min(cur_arr) == max(cur_arr):
        return True
    else:
        for iter, item in enumerate(cur_arr):
            if iter!=m:
                cur_arr[iter] = cur_arr[iter]-abs(m-iter)
                # print(iter)
                # print(cur_arr)
                if canEqual(cur_arr, iter):
                    return True
                else:
                    cur_arr[iter] = cur_arr[iter]+abs(m-iter)
    return False
print(canEqual([2, 2, 4, 2, 2], 2))

输出:

True

推荐阅读