简体   繁体   English

如何在列表中找到所有等于 N 的对

[英]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:我会使用的算法是:

  • create counter of elements in list在列表中创建元素计数器
  • iterate list迭代列表
    • for each element, check if (target - element) exists in counter and count of that item > 0对于每个元素,检查 (target - element) 是否存在于计数器中,并且该项目的计数 > 0
      • decrement count of element and (target - element)减少元素的计数和(目标 - 元素)

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]]

Demo演示

To fix your code - few remarks:要修复您的代码 - 几句话:

  1. 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循环)

  2. 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:临:

  • It does make the time complexity linear.它确实使时间复杂度线性化。
  • Doesn't modify the input不修改输入

Cons:缺点:

  • Uses extra space使用额外空间
  • Uses a different strategy from the original.使用与原始策略不同的策略。 If this is for a class and you haven't learned about the data structures applied then don't use this.如果这是针对 class 并且您还没有了解应用的数据结构,请不要使用它。

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.

相关问题 如何从python中的列表中获取所有单独的所有相等对 - How to get all seperate all equal pairs from a list in python 如何在列表中找到成对的整数,这些整数加起来为 O(N) 中的目标? - How to find pairs of integers in a list that add up to a target in O(N)? 查找日期是否在N对列表中重叠 - Find if dates are overlapping in a list of N pairs 如何检查嵌套列表中的所有数字是否都等于 n - How to check if all numbers in a nested list are equal to n 如何在python中创建一个包含所有可能对的次数相等的列表序列? - how to create a list sequence in python containing all possible pairs an equal number of times? 查找列表中的所有对,条件为 Python - Find all the pairs in a list with conditions Python 如何在数组中找到N个连续数字相等? - How to find N consecutive numbers are equal in array? 给定一个由 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 如何将列表分成n个相等的部分,python - How to divide a list into n equal parts, python 如何遍历 n 维列表并找到所有组合 - How to loop through an n-dimensional list and find all combinations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM