在下面的子問題,我試圖做一個列表對象蟒蛇列表不會複製
def findFourPlus(itemCount, seq, goal):
goalDifference = float("inf")
closestPartial = []
subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial=[])
print(closestPartial)
def subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial):
s = sum(partial)
# check if the partial sum is equals to target
if(len(partial) == itemCount):
if s == goal:
print(partial)
else:
if(abs(goal - s) < goalDifference):
goalDifference = abs(goal - s)
print(goalDifference)
print(partial)
print(closestPartial)
closestPartial = copy.deepcopy(partial)
for i in range(len(seq)):
n = seq[i]
remaining = seq[i+1:]
subset_sum(itemCount, remaining, goal, goalDifference, closestPartial, partial + [n])
子集中的功能
的副本,我試圖做的partial
副本列表到closestPartial
。我試過
closestPartial = partial
closestPartial = list[:]
closestPartial = list(partial)
closestPartial = copy.copy(partial)
closestPartial = copy.deepcopy(partial)
但是最後他們都看起來是徒勞的。由於某種原因,最接近的部分仍然是一個空列表(這是我發起的)
不是這樣做的: closestPartial = partial? – 2014-09-22 02:59:04
嗨@Yousef_Shamshoum - 看我的更新。 'nearestPartial = partial'將局部變量賦給名爲closestPartial的局部變量。你想要更新的東西 - 也就是說,在分配之前最接近的部分 - 丟失了。 – tdelaney 2014-09-22 03:01:16
...'[:]'符號在原地進行替換。 – tdelaney 2014-09-22 03:02:03