gpt4 book ai didi

python - Python 中的递归回溯——在天平上平衡权重

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:00 25 4
gpt4 key购买 nike

问题: 假设您在秤的一侧有一个重量。给定一系列其他权重,看看天平是否会平衡。您可以在任一侧使用权重,而不必使用所有权重。

在我当前的解决方案中,每个级别都有 3 个分支。第一个将数组中的第一个权重添加到“左侧”,第二个简单地丢弃它,第三个将它添加到“右侧”。我的问题似乎是,在完成第一个分支后,如果所有分支结果都是 False,它会返回 False。相反,我希望它移动到下一个分支。

给我提示的是,当我有 weights = [4,1]init_weight = 3 时,它给了我错误的消息(说它无法平衡),但是当我将权重顺序翻转为 [1,4] 时,它会给我正确的消息。

我昨天才开始学习 Python,所以我猜我错过了某种微妙的句法。但这绝对不排除算法问题!

def balanceable_rec(L, R, weights):

print("L =", L, " R =", R, " weights =", weights)

if (L == 0 or L==R or L in weights):
return True
if (len(weights) == 0):
return False

w = weights.pop(0)
if balanceable_rec(L + w, R, weights): return True
if balanceable_rec(L, R, weights): return True
if balanceable_rec(L, R + w, weights): return True

return False


def balanceable(w, weights):
return balanceable_rec(w, 0, weights)


# ----------------------

# weights = [1,4]
weights = [4,1]
init_weight = 3

if (balanceable(init_weight, weights)): print("That can be balanced!")
else: print("That cannot be balanced!")

这是输出:

L = 3 R = 0 weights = [4, 1]

L = 7 R = 0 weights = [1]

L = 8 R = 0 weights = []

L = 7 R = 0 weights = []

L = 7 R = 1 weights = []

L = 3 R = 0 weights = []

L = 3 R = 4 weights = []

That cannot be balanced!

最佳答案

您需要将 weights 的副本传递给您的递归调用,以便 pop 调用不会影响原始 weights 对象,例如:

def balanceable_rec(L, R, weights):

print("L =", L, " R =", R, " weights =", weights)

if (L == 0 or L==R or L in weights):
return True
if (len(weights) == 0):
return False

w = weights.pop(0)
if balanceable_rec(L + w, R, weights[:]): return True
if balanceable_rec(L, R, weights[:]): return True
if balanceable_rec(L, R + w, weights[:]): return True

return False

关于python - Python 中的递归回溯——在天平上平衡权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22527379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com