Search code examples
pythoninsertion

I cant see if my list has repeated numbers in it


I'm trying to generate 20 random numbers in my list. Next I want to see if there are any repeated numbers in it.

I generated the random numbers. Next I did an insertion sort in order to arrange the list in a growing order. To see if I had any repeated numbers, I iterated over the list and if the previous number was equal to the next number, then my list had repeated numbers in it.

import random

random_array=[]

def array():
  for i in range(0,20):
    random_element=random.randint(1,35)
    random_array.append(random_element)
  return random_array
print(array())

# function to order the list
def insertion_sort():
  for i in range(1,len(random_array)):
    while i>0 and random_array[i-1]>random_array[i]:
      random_array[i-1],random_array[i]=random_array[i],random_array[i-1]
      i=i-1
  return random_array
print(insertion_sort())

def verification():
  for i in random_array:
    insertion_sort()
    if i-1==i:
      return True
    else:
      return False
print(verification())

My program always returns false independent of the generated list.


Solution

  • You can do it with much shorter code using itertools.Counter:

    import random
    from collections import Counter
    
    # Generate a random array
    random_array = [random.randint(1, 35) for _ in range(20)]
    
    
    nums = [
        n  # A number
        for (n, count) in Counter(random_array).items()  # From countered items
        if count > 1  # If the count of this number is more than one
    ]
    print(nums)