[英]How to write a general function to find those elements of array whose sum is zero?
I have created a program which that takes as input an array of positive and negative numbers (0 excluded) and return those items from the array whose sum is 0. If no such items exist return, then return “No Elements found”.我创建了一个程序,它将正数和负数数组(不包括 0)作为输入,并返回数组中总和为 0 的那些项。如果不存在此类项,则返回,然后返回“未找到元素”。 Here I have written separate functions for twoSum, threeSUM, fourSum... but I want to have general function which will check for nSum (n is the number of elements of array) eg In this list [-4, -3, -2, -1, 10], it should return -4, -3, -2, -1 and 10 there are 5 elements whose sum is 0. I am sharing my code.
在这里,我为 twoSum、threeSUM、fourSum 编写了单独的函数...但我想要通用的 function 来检查 nSum(n 是数组元素的数量),例如在此列表中 [-4、-3、-2 , -1, 10], 它应该返回 -4, -3, -2, -1 和 10 有 5 个元素的总和为 0。我正在分享我的代码。
def twoSum(arr,n,x,lp,rp):
while lp<rp:
if arr[lp] + arr[rp] == x:
return True,arr[lp],arr[rp]
elif arr[lp] + arr[rp] < x:
lp+=1
else:
rp-=1
return False,0,0
def threeSum(arr,n,x,firstIndex):
for i in range(firstIndex,n-2):
check,a,b = twoSum(arr,n,x-arr[i],i+1,n-1)
if check:
return True,arr[i],a,b
return False,0,0,0
def finding_numbers(arr, n):
if arr[0]<0:
check,a,b = twoSum(arr,n,0,0,n-1)
if check:
return a,b
check,a,b,c = threeSum(arr,n,0,0)
if check:
return a,b,c
for i in range(n-3):
check,a,b,c = threeSum(arr,n,-arr[i],i+1)
if check:
return arr[i],a,b,c
return 'No Elements found'
finding_numbers(array, n)
You can use the help of the combinations function from itertools:您可以使用 itertools 中组合function 的帮助:
from itertools import combinations
def combinations_that_sum_zero(arr):
return [list(comb) for i in range(1, len(arr) + 1) for comb in combinations(arr, i) if sum(comb) == 0]
arr = [1, 2, 3, -3, 4, 5, -6]
print(combinations_that_sum_zero(arr))
[[3, -3], [1, 2, -3], [1, 5, -6], [2, 4, -6], [1, 2, 3, -6], [-3, 4, 5, -6], [1, 3, -3, 5, -6], [2, 3, -3, 4, -6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.