Program to find missing numbers from two list of numbers in Python

PythonServer Side ProgrammingProgramming

Suppose we have two list of numbers say nums1 and nums2. There are some elements not necessarily unique. But these two lists are actually representing different permutations of same set of numbers. However, some of them are missing. We have to find missing numbers of these two lists and print them all.

So, if the input is like nums1 = [4,5,8,8,6,9] nums2 = [3,4,4,8,8,8,6,9,5,8], then the output will be [3,4,8,8] because we can see 3 is not present in nums1, but it is in nums2, so it is missing. 4 is present in both but in nums2 there two 4s but in nums1 there is only one, so one 4 is missing. Similarly nums2 has four 8s, but in nums1 there are only 2, so two are missing.

To solve this, we will follow these steps −

  • c1 := a list containing frequencies of each elements present in nums1
  • c2 := a list containing frequencies of each elements present in nums2
  • all_nums := a set containing all distinct numbers from nums1 and nums2
  • res := a new list
  • for each n in all_nums, do
    • if n not in c1, then
      • insert n, c2[n] times into res
    • otherwise when n not in c2, then
      • insert n, c1[n] times into res
    • otherwise,
      • if c1[n] is not same as c2[n], then
        • insert n, |c1[n]- c2[n]| times into res
  • return res

Example

Let us see the following implementation to get better understanding −

from collections import Counter

def solve(nums1, nums2):
   c1 = Counter(nums1)
   c2 = Counter(nums2)
   all_nums = set(nums1) | set(nums2)
   res = []
   for n in all_nums:
      if n not in c1:
         res = res + [n]*c2[n]
      elif n not in c2:
         res = res + [n]*c1[n]
      else:
         if c1[n] != c2[n]:
            res = res + [n]*abs(c1[n]- c2[n])
   return res

nums1 = [4,5,8,8,6,9]
nums2 = [3,4,4,8,8,8,6,9,5,8]
print(solve(nums1, nums2))

Input

[4,5,8,8,6,9], [3,4,4,8,8,8,6,9,5,8]

Output

[3, 4, 8, 8]
raja
Published on 12-Oct-2021 09:13:00
Advertisements