Home > Back-end >  Finding numbers that cannot be paired
Finding numbers that cannot be paired

Time:06-11

I've a function which aim is to find numbers that you cannot pair with others. If a number cannot be paired up with another identical number, then you will have to return it.

example:

[1,1,1,1, 2, 3, 4]

expected result:

[2,3,4]
def pair(input):
    while len(input) > 2:
        for i in range(len(input) - 1):
            for j in range(len(input) - 1):
                print(input)
                if input[i] == input[j]:
                    input.pop(i)
                    input.pop(j)
                    print(input)
                else:
                    break
            
        return input


print(pair([1,1,1,1, 2, 3, 4]))

CodePudding user response:

If you can use a library, you could use a Counter from collections, and just return the values in the list that have an odd count (since that implies there is one of those numbers that cannot be paired with another):

from collections import Counter

ll = [ 1, 2, 1, 3, 2, 3, 1, 4, 1, 2, 3, 4 ]
c = Counter(ll)
[num for num, cnt in c.items() if cnt % 2 == 1]

Output:

[2, 3]

CodePudding user response:

One way to solve this problem is to find the unique elements in the list, and if an element occurs an odd number of times the in the list, returned it.

def pair(lst):
    set_lst = set(lst)
    output = []
    for elem in set_lst:
        if lst.count(elem) % 2 != 0:
            output.append(elem)
    return output


print(pair([1, 1, 1, 1, 2, 3, 4]))

CodePudding user response:

Keeping track of the numbers that occurred an odd number of times:

def pair(lst):
    odd = set()
    for x in lst:
        odd ^= {x}
    return list(odd)

print(pair([1,1,1,1, 2, 3, 4]))

CodePudding user response:

According your example input list is sorted. In this case @KetZoomer's solution is not effective, because it searching for the elem in whole list and counting it every time (lst.count(elem))

If you counted number of 1's you don't need to search for 2 in whole list from 0th element to last element again.

You should to use something like this:

def pairs(lst: list) -> list:
  if len(lst) > 0:
    # set first element
    current_el = lst[0]
    duplicate_count = 1
    values_without_pair = []
  else:
    return []

  # loop for elements starting from 2nd
  for i in range(1, len(lst)):
    # if looped element same as stored in memory increase count and go to next element
    if current_el == lst[i]:
      duplicate_count  = 1
    # if element is changed then check count value is even or not
    # and set new element for checking
    else:
      if duplicate_count % 2 != 0:
        values_without_pair.append(current_el)
      duplicate_count = 1
      current_el = lst[i]

  # process last element
  if duplicate_count % 2 != 0:
    values_without_pair.append(current_el)

  return values_without_pair


print(pairs([1,1,1,1,2,3,4]))
  • Related