Home > Back-end >  print all repeated numbers
print all repeated numbers

Time:10-11

My intent is for this code to print out all repeated numbers and then state how many times each number is repeated. Here is my code:

i = [5,5,7,9,9,9,9,9]
def num_list(i):
    for x in (i):
        if i.count(x) > 1:
            return (i.count(x), x)
print(num_list(i))

However, when I run the code, only the first repeated number is printed, displayed as (2, 5). Since 9 is also a repeated number, I want both (2, 5) and (5, 9) to be printed. What code modifications are needed?

CodePudding user response:

You return as soon as you hit a value with a count greater than 1. Instead, map everything to a tuple of x and count (I reversed them). And validate the count after the fact. Something like

i = [5,5,7,9,9,9,9,9]
def num_list(i):
    return [(x,i.count(x)) for x in set(i)]

for tv in num_list(i):
    if tv[1] > 1:
        print(tv)

And I get

(9, 5)
(5, 2)

Because there are 5 nines and 2 fives.

CodePudding user response:

You're returning when a single duplicate value is found. After then it's not checking the whole array. Use a set() and add if found any duplicate value and return it to the end of the loop.

i = [5,5,7,9,9,9,9,9]
def num_list(i):
    s=set()
    for x in (i):
        if i.count(x) > 1:
            s.add( (i.count(x), x))
    return s
print(num_list(i))

Output

{(5, 9), (2, 5)}
  • Related