[英]How to find the specific numbers in a list with a sum of a particular sum with Python
我有一个数字列表:
[40.5, 19.04, 31.72, 68.16, 45.68, 45.68, 532.74, 137.52, 401.58, 25.92, 185.90, 1037.96, 23.41, 829.50, 98.35, 57.12, 620.87, 21, 435.08, 460.85, 1079.16, 1386.29, 272.82, 131.44, 135.51, 39, 1079.16, 230.63, 1297.44, 301.27, 372.57,173.17, 191.84, 213.92, 423.9, 56.24, 189.98, 14.76]
我在列表中有一些特定数字的总和,我如何得到已知总和的数字?
例如,如果知道总和是 59.04,我如何找出 40.5 和 19.04?
干杯!
使用它来查找和对
def findPair(A, sum):
for i in range(len(A) - 1):# consider each element except last element
for j in range(i + 1, len(A)):# start from i'th element till last element
if A[i] + A[j] == sum:# if desired sum is found, print it and return
print("Pair found at index", i, "and", j)
print("Sum Pair:", A[i], A[j])
return
print("Pair not found")# No pair with given sum exists in the list
A = [40.5, 19.04, 31.72, 68.16, 45.68, 45.68, 532.74, 137.52, 401.58, 25.92, 185.90, 1037.96, 23.41, 829.50, 98.35, 57.12, 620.87, 21, 435.08, 460.85, 1079.16, 1386.29, 272.82, 131.44, 135.51, 39, 1079.16, 230.63, 1297.44, 301.27, 372.57,173.17, 191.84, 213.92, 423.9, 56.24, 189.98, 14.76]
findPair(A, 59.54)
sum = 99.88
findPair(A, sum)
Output:
Pair found at index 0 and 1
Sum Pair: 40.5 19.04
Pair found at index 2 and 3
Sum Pair: 31.72 68.16
参考: https://www.techiedelight.com/find-pair-with-given-sum-array/
N 个数字的总和:
import itertools
def findlist(A, summ):
for i in range(len(A)):
for j in itertools.combinations(A, i):
res = round(sum(list(j)), 2)
if res == summ:
print("Sum Combinations", j )
A = [40.5, 19.04, 31.72, 68.16, 45.68]
findlist(A, 91.26)
注意:对于大型列表,这会比较慢
is_sum = lambda seq, x: any(x == y + z for yi, y in enumerate(seq) for zi, z in enumerate(seq) if zi != yi)
>>> is_sum([40.5, 19.04, 31.72, 68.16, 45.68, 45.68, 532.74, 137.52, 401.58, 25.92, 185.90, 1037.96, 23.41, 829.50, 98.35, 57.12, 620.87, 21, 435.08, 460.85, 1079.16, 1386.29, 272.82, 131.44, 135.51, 39, 1079.16, 230.63, 1297.44, 301.27, 372.57,173.17, 191.84, 213.92, 423.9, 56.24, 189.98, 14.76], 59.04)
True
只需使用 itertools,
import itertools
listofnumbers = [40.5, 19.04, 31.72, 68.16, 45.68, 45.68, 532.74, 137.52, 401.58, 25.92, 185.90, 1037.96, 23.41, 829.50, 98.35, 57.12, 620.87, 21, 435.08, 460.85, 1079.16, 1386.29, 272.82, 131.44, 135.51, 39, 1079.16, 230.63, 1297.44, 301.27, 372.57,173.17, 191.84, 213.92, 423.9, 56.24, 189.98, 14.76]
target = 59.54
for numbers in itertools.combinations(listofnumbers,2):
if round(sum(numbers),2) == target:
print(numbers)
指定 2 个数字,您的 output 将是
(40.5, 19.04)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.