查找列表中的四个数字,这些数字总计达到目标值

时间:2015-08-17 02:09:14

标签: python algorithm list list-comprehension duplicate-removal

以下是我为解决此问题而编写的代码:在列表中找到最多x的四个数字。

def sum_of_four(mylist, x):
    twoSum = {i+j:[i,j] for i in mylist for j in mylist}
    four = [twoSum[i]+twoSum[x-i] for i in twoSum if x-i in twoSum]
    print four
sum_of_four([2, 4, 1, 1, 4, 6, 3, 8], 8)

我得到的样本输入答案是:

[[1, 1, 3, 3], [1, 2, 3, 2], [3, 1, 3, 1], [3, 2, 1, 2], [3, 3, 1, 1]]

但是,此列表列表包含重复项。例如,[1,1,3,3][3,3,1,1]相同。

如何打印没有重复列表的列表列表?我希望在运行时和空间中尽可能高效。是否可以更改我的列表理解,以便我不打印重复项?我当然不想对列表进行排序,然后使用set()删除重复项。我想做点好事。

2 个答案:

答案 0 :(得分:1)

通过计算输入列表中每个值出现的次数,可以开始正确且相对有效的方法。假设value出现count次。然后,您可以将countvalue个副本附加到您构建选择值的列表中。在附加value的任何副本之前,在附加每个副本之后,进行递归调用以继续下一个值。

我们可以按如下方式实施这种方法:

length = 4

# Requires that frequencies be a list of (value, count) sorted by value.
def doit(frequencies, index, selection, sum, target, selections):
  if index == len(frequencies):
    return
  doit(frequencies, index + 1, selection[:], sum, target, selections)  # Skip this value.
  value, count = frequencies[index]
  for i in range(count):
    selection.append(value)
    sum += value
    if sum > target:
      return  # Quit early because all remaining values can only be bigger.
    if len(selection) == length:
      if sum == target:
        selections.append(selection)
      return  # Quit because the selection can only get longer.
    doit(frequencies, index + 1, selection[:], sum, target, selections)  # Use these values.

def sum_of_length(values, target):
  frequency = {}
  for value in values:
    frequency[value] = frequency.setdefault(value, 0) + 1
  frequencies = sorted(frequency.items())  # Sorting allows for a more efficient search.
  print('frequencies:', frequencies)
  selections = []
  doit(frequencies, 0, [], 0, target, selections)
  return list(reversed(selections))

print(sum_of_length([2, 4, 1, 1, 4, 6, 3, 8], 8))
print(sum_of_length([1, 1, 1, 2, 2, 3, 3, 4], 8))
print(sum_of_length([-1, -1, 0, 0, 1, 1, 2, 2, 3, 4], 3))

顺便说一下,样本输入的正确答案是[[1, 1, 2, 4]]。只有一种方法可以从[2, 4, 1, 1, 4, 6, 3, 8]中选择四个元素,使它们的总和为8。

答案 1 :(得分:0)

如果您希望多次重复使用这些数字,例如您的示例答案,而您在列表中只有一个3,但您有[1,1,3,3]作为解决方案,那么您可以尝试:

def sum_of_four(list, x, y, curr=[]):
if y == 1:
    for l in list:
        if l == x:
            d = curr[:]
            d.append(l)
            print(d)
            break
else:
    for i in range(len(list)):
        l = list[i]
        if l <= (x - l) / (y - 1):
            d = curr[:]
            d.append(l)
            sum_of_four(list[i:], x-l, y-1, d)

sum_of_four(sorted([2,4,1,4,6,3,8]),8,4)