[英]How find all pairs equal to N in a list
I have a problem with this algorithm- I have to find pairs in list:我对这个算法有疑问-我必须在列表中找到对:
[4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0]
which are equal to 12
.等于
12
。 The thing is that after making a pair those numbers (elements) can not be used again.问题是,在配对之后,这些数字(元素)不能再次使用。
For now, I have code which you can find below.现在,我有你可以在下面找到的代码。 I have tried to delete numbers from the list after matching, but I feel that there is an issue with indexing after this.
我尝试在匹配后从列表中删除数字,但我觉得在此之后索引存在问题。
It looks very easy but still not working.它看起来很容易,但仍然无法正常工作。
;/
class Pairs():
def __init__(self, sum, n, arr ):
self.sum = sum
self.n = n
self.arr = arr
def find_pairs(self):
self.n = len(self.arr)
for i in range(0, self.n):
for j in range(i+1, self.n):
if (self.arr[i] + self.arr[j] == self.sum):
print("[", self.arr[i], ",", " ", self.arr[j], "]", sep = "")
self.arr.pop(i)
self.arr.pop(j-1)
self.n = len(self.arr)
i+=1
def Main():
sum = 12
arr = [4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0]
n = len(arr)
obj_Pairs = Pairs(sum, n, arr)
obj_Pairs.find_pairs()
if __name__ == "__main__":
Main()
update:更新:
Thank you guys for the fast answers!谢谢你们的快速回答!
I've tried your solutions, and unfortunately, it is still not exactly what I'm looking for.我已经尝试了您的解决方案,不幸的是,它仍然不是我想要的。 I know that the expected output should look like this: [4, 8], [0, 12], [1, 11], [4, 8], [12, 0].
我知道预期的 output 应该是这样的:[4, 8], [0, 12], [1, 11], [4, 8], [12, 0]。 So in your first solution, there is still an issue with duplicated elements, and in the second one [4, 8] and [12, 0] are missing.
因此,在您的第一个解决方案中,重复元素仍然存在问题,而在第二个解决方案中,缺少 [4, 8] 和 [12, 0]。 Sorry for not giving output at the beginning.
很抱歉一开始没有给 output。
With this problem you need to keep track of what numbers have already been tried.对于这个问题,您需要跟踪已经尝试过的数字。 Python has a Counter class that will hold the count of each of the elements present in a given list.
Python 有一个计数器class 将保存给定列表中存在的每个元素的计数。
The algorithm I would use is:我会使用的算法是:
from collections import Counter
class Pairs():
def __init__(self, target, arr):
self.target = target
self.arr = arr
def find_pairs(self):
count_dict = Counter(self.arr)
result = []
for num in self.arr:
if count_dict[num] > 0:
difference = self.target - num
if difference in count_dict and count_dict[difference] > 0:
result.append([num, difference])
count_dict[num] -= 1
count_dict[difference] -= 1
return result
if __name__ == "__main__":
arr = [4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0]
obj_Pairs = Pairs(12, arr)
result = obj_Pairs.find_pairs()
print(result)
Output: Output:
[[4, 8], [8, 4], [0, 12], [12, 0], [1, 11]]
To fix your code - few remarks:要修复您的代码 - 几句话:
If you iterate over array in for
loop you shouldn't be changing it - use while
loop if you want to modify the underlying list (you can rewrite this solution to use while
loop)如果您在
for
循环中迭代数组,则不应更改它 - 如果您想修改底层列表,请使用while
循环(您可以重写此解决方案以使用while
循环)
Because you're iterating only once the elements in the outer loop - you only need to ensure you "popped" elements in the inner loop.因为您只迭代外循环中的元素一次 - 您只需要确保您“弹出”内循环中的元素。
So the code:所以代码:
class Pairs():
def __init__(self, sum, arr ):
self.sum = sum
self.arr = arr
self.n = len(arr)
def find_pairs(self):
j_pop = []
for i in range(0, self.n):
for j in range(i+1, self.n):
if (self.arr[i] + self.arr[j] == self.sum) and (j not in j_pop):
print("[", self.arr[i], ",", " ", self.arr[j], "]", sep = "")
j_pop.append(j)
def Main():
sum = 12
arr = [4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0]
obj_Pairs = Pairs(sum, arr)
obj_Pairs.find_pairs()
if __name__ == "__main__":
Main()
Brief简短的
If you have learned about hashmaps and linked lists/deques, you can consider using auxiliary space to map values to their indices.如果您了解哈希图和链表/双端队列,您可以考虑使用辅助空间将 map 值添加到它们的索引中。
Pro:临:
Cons:缺点:
Code代码
from collections import deque # two-ended linked list
class Pairs():
def __init__(self, sum, n, arr ):
self.sum = sum
self.n = n
self.arr = arr
def find_pairs(self):
mp = {} # take advantage of a map of values to their indices
res = [] # resultant pair list
for idx, elm in enumerate(self.arr):
if mp.get(elm, None) is None:
mp[elm] = deque() # index list is actually a two-ended linked list
mp[elm].append(idx) # insert this element
comp_elm = self.sum - elm # value that matches
if mp.get(comp_elm, None) is not None and mp[comp_elm]: # there is no match
# match left->right
res.append((comp_elm, elm))
mp[comp_elm].popleft()
mp[elm].pop()
for pair in res: # Display
print("[", pair[0], ",", " ", pair[1], "]", sep = "")
# in case you want to do further processing
return res
def Main():
sum = 12
arr = [4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0]
n = len(arr)
obj_Pairs = Pairs(sum, n, arr)
obj_Pairs.find_pairs()
if __name__ == "__main__":
Main()
Output Output
$ python source.py
[4, 8]
[0, 12]
[4, 8]
[1, 11]
[12, 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.