检查Integer数组是否可以在Python中使用递归进行均衡



给定一个大小为5、具有任意正值的integer arraym,我的任务是创建一个程序,检查是否可以通过以下过程均衡此数组(所有整数都相等(:

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)   

我真的不确定我处理这个问题的方法是否正确。

看一看(并尝试通过调查来更好地理解它(,取消对两个打印的注释以更好地理解过程,如果有什么对你来说没有意义,请要求澄清。

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

最新更新