简体   繁体   English

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

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

I am making an algorithm that can get an element or a list of elements from a list that is equal or whose sum is equal to a given number.我正在制作一种算法,该算法可以从列表中获取一个元素或元素列表,该列表等于或其总和等于给定数字。

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)

From list1 want the elements that sum up 3, but my goal is to find if that exact number like say 3 is in the list, then select it else select other numbers that sum up to 3.list1想要总和为 3 的元素,但我的目标是找出像 3 这样的确切数字是否在列表中,然后是 select 否则 select 其他数字总和为 3。

From list2 I need a value equal to 130 or elements that sum up to 130, as you see there are no values that match so I need to select an element thats closest match to it say 150 then save it to another array.list2我需要一个等于 130 的值或总和为 130 的元素,如您所见,没有匹配的值,所以我需要 select 一个与其最接近的匹配元素,例如 150,然后将其保存到另一个数组。 NB: Plz not that there's no limit on elements to combine, as long as the elements total up to the required number but i would prefer to first look in the list to see if there's an exact number matching.注意:请不要说要组合的元素没有限制,只要元素总数达到所需的数量,但我更愿意先查看列表中是否有确切的数字匹配。

Below is the code I am using but I can only get the values that sum up, I need help to solve the more complex solutions.下面是我正在使用的代码,但我只能得到总结的值,我需要帮助来解决更复杂的解决方案。

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)

There's probably no better way then to test all the combinations of 1, 2, 3, ... elements of the list whether they match the given target sum.可能没有更好的方法来测试列表中 1、2、3、... 元素的所有组合是否与给定的目标总和匹配。 However, you can combine your three cases (perfect match, matching sum, and nearest sum) by using a tuple (difference to target, number of element) as the key to be minimized.但是,您可以通过使用元组(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)

Here, n is the maximum number of elements to combine.这里, n是要组合的最大元素数。 You can of course also use a higher value than 3 , but for longer lists, this will mean that there are a lot more elements to compare.当然,您也可以使用比3更高的值,但对于更长的列表,这意味着比较的元素更多。 Also, note that this function will not stop early if a perfect match is found, although this could be achieved using a regular loop instead of min .另外,请注意,如果找到完美匹配,则此 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]

Similarly, you can tweak the combs function to not just generate all the combinations, but to abort early, eg if the sum of a combination is already larger than the target sum, then adding more numbers to that combination will not make it better -- but still other longer combinations could be better.同样,您可以调整combs function 以不仅生成所有组合,而且提前中止,例如,如果组合的总和已经大于目标总和,那么向该组合添加更多数字不会使其更好 -但其他更长的组合可能会更好。 However, this will only work for this specific target function, and only if there are no negative numbers in the list.但是,这只适用于这个特定的目标 function,并且只有在列表中没有负数的情况下。

As I've understood, your requirement is to either search and find a number from a list, or display the numbers needed from the list to sum up to get the input number.据我了解,您的要求是从列表中搜索并查找一个数字,或者显示列表中需要的数字以求和以获得输入数字。 Correct me if I am wrong.如果我错了,请纠正我。

If that's the case, you can get the total sum, and count in this way using Python3:如果是这种情况,您可以得到总和,并使用 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.

相关问题 如何打印列表的元素,其总和等于 python 中的给定数字? - how to print elements of a list whose sum is equal to a given number in python? 检查列表中的元素是否等于列表的总和值 - Check if elements in a list equal to the sum value of the list 列表中总和等于或小于给定数字的元素列表 - list of elements from a list that sum is equal or less than to a given number 子数组元素的总和等于 Python 中的目标值 - Sum of elements of subarrays is equal to a target value in Python 编辑数组元素的总和以等于 Python 中的值 - Editing the sum of array elements to equal a value in Python 给定一个数组; 我需要子阵列; 其元素的XOR值等于某个给定值 - Given an array; I need the sub-arrays; whose elements' XOR value is equal to some given value 从4个给定的数组(未排序)中,找到每个数组的元素,其总和等于某个数字X. - From 4 given arrays(not sorted), find the elements from each array whose sum is equal to some number X 给定一个由 N 个整数组成的数组和一个整数 K,找出该数组中总和等于 K 的元素对的数量 - Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K Python:具有多个条件的熊猫总和 - Python : Pandas Sum with more than one condition 总和小于给定总和的最大子集 - Largest Subset whose sum is less than equal to a given sum
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM