簡體   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