【问题标题】:How to add the same element N times? [closed]如何将相同的元素添加 N 次? [关闭]
【发布时间】:2017-10-10 00:02:45
【问题描述】:

我有两个列表:

list1 = [1,2,6]
list2 = []

我有一个数字:N

如何将 list1 的数字附加到 list2 以使 list2 的总和等于 N。

示例:

n = 10
list2 = [2,2,6]

在总和等于 10 之前,我找不到将 2 相加的方法

【问题讨论】:

  • 听起来像是一个动态规划问题
  • 当你无法达到 N 的值时会发生什么?
  • 一旦有大于0的元素总是可以的
  • @taynan 不,不会。如果 1 在集合中,那么当然是可能的,但是如果例如所有的数字都是偶数,目标数是奇数,那么这是不可能的。

标签: python-3.x list


【解决方案1】:

这可能有效:

list1 = [1,2,6]
list2 = []
n = 10

list1 = sorted(list1, reverse=True) # sort list descending order

for i in list1:                     # for each item in list1
    list2.append(i)                 # add the item to list2
    while not sum(list2) >  n:      # while sum of list2 is less than n 
        list2.append(i)             # keep adding the same element
    if sum(list2) > n:              # if sum of list2 is more than n
        list2.pop()                 # remove the last element added

list2.sort() # sort list ascending order
print(list2) # [2, 2, 6]

适用于给定的list1

可能需要测试不同长度和数量的list1

【讨论】:

  • 哇,这个人太棒了,它正在工作。我曾尝试做类似的事情,但是“虽然不是 sum(list2) > n:”,但我尝试了“while sum(list2)
  • 是的,你可以用 "while sum(list2)
  • 反转列表真是个好主意O.O
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多