繁体   English   中英

Python 列表中的一个或多个元素的和或值等于给定条件

[英]Python one or more elements in a list whose sum or value is equal to a given condition

我正在制作一种算法,该算法可以从列表中获取一个元素或元素列表,该列表等于或其总和等于给定数字。

list1 = [1,1, 1, 1,2,3,3,4,7,8,9, 45, 67, 98] (Sum up to 3)

list2 = [5,40, 70, 120, 150]      (Sum up to 130)

list1想要总和为 3 的元素,但我的目标是找出像 3 这样的确切数字是否在列表中,然后是 select 否则 select 其他数字总和为 3。

list2我需要一个等于 130 的值或总和为 130 的元素,如您所见,没有匹配的值,所以我需要 select 一个与其最接近的匹配元素,例如 150,然后将其保存到另一个数组。 注意:请不要说要组合的元素没有限制,只要元素总数达到所需的数量,但我更愿意先查看列表中是否有确切的数字匹配。

下面是我正在使用的代码,但我只能得到总结的值,我需要帮助来解决更复杂的解决方案。

class select_pair():
  def __init__(self, l, target):
  self.__l = l
  self.__target = target
  if not isinstance(l, list):
  raise TypeError("it must be a list")
  elif not isinstance(target, int):
  raise TypeError("it must be an integer")
  for i in range(len(l)-1):

  if l[i] == target:  
    print("from 1st index1:{}".format(i))
    break
  elif l[i]+l[i+1] == target:
   print("from second index1:{}, index2:{}".format(i+1, i+2))
   break


p = select_pair(list1,3)
p = select_pair(list2,130)

可能没有更好的方法来测试列表中 1、2、3、... 元素的所有组合是否与给定的目标总和匹配。 但是,您可以通过使用元组(difference to target, number of element)作为要最小化的键来组合您的三种情况(完全匹配、匹配和和最接近的和)。

from itertools import combinations    
def combs(lst, n):
    return (c for k in range(1, n+1) for c in combinations(lst, k))

def best_match(lst, target, n=3):
    return min(combs(lst, n), key=lambda c: (abs(target - sum(c)), len(c)))

list1 = [1,1, 1, 1,2,3,3,4,7,8,9, 45, 67, 98]
list2 = [5,40, 70, 120, 150]
print(best_match(list1, 3))   # (3,)
print(best_match(list2, 130)) # (5, 120)

这里, n是要组合的最大元素数。 当然,您也可以使用比3更高的值,但对于更长的列表,这意味着比较的元素更多。 另外,请注意,如果找到完美匹配,则此 function 不会提前停止,尽管这可以使用常规循环而不是min来实现。

def best_match_stop_early(lst, target, n=3):
    best = None
    for c in combs(lst, n):
        v = (abs(target - sum(c)), len(c), c)
        if best is None or v < best:
            best = v
            if v[0] == 0:
                return v[2]
    return best[2]

同样,您可以调整combs function 以不仅生成所有组合,而且提前中止,例如,如果组合的总和已经大于目标总和,那么向该组合添加更多数字不会使其更好 -但其他更长的组合可能会更好。 但是,这只适用于这个特定的目标 function,并且只有在列表中没有负数的情况下。

据我了解,您的要求是从列表中搜索并查找一个数字,或者显示列表中需要的数字以求和以获得输入数字。 如果我错了,请纠正我。

如果是这种情况,您可以得到总和,并使用 Python3 以这种方式计算:

list1 = [1,1, 1, 1,2,3,3,4,7,8,9, 45, 67, 98]
input_number = int(input("Enter the number: "))

count = 0
total = 0

if input_number in list1:
    print(f"{input_number} found !")
else:
    for i in list1:
        count+=1
        total+=i
        if total >= input_number:
            print(f"Total is {total}")
            print(f"First {count} numbers from the list were added. ")
            break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM