python - 检查是否可以在 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)
我不确定我解决这个问题的方法是否正确。
解决方案
看一下(并尝试通过调查更好地理解它),取消注释这两个打印以更好地理解该过程,如果某些事情对您没有意义,请要求澄清。
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
推荐阅读
- assembly - 为什么这个阶乘程序给出的结果较低?
- mysql - SQL处理子查询错误代码:1111
- javascript - 将具有未知键的字典转换为 Earh 引擎中的特征集合
- scip - SCIP 如何计算 vanillafullstrongbranching-scores?
- javascript - 点击打开菜单
- opengl - 不做 glDeleteBuffers 和其他 OpenGL (3.3) 清理可以吗?
- javascript - 在 d3 力模拟中,有没有办法强制远离某些固定点?
- version - OpenLayers 版本 5.3.0,地图导出 pdf 的问题
- python - Pipeline GridSearchCV,不同步骤对应的参数
- hive - 如何将本地蜂巢连接到雪花?