Nutnicha
Nutnicha

Reputation: 285

print all repeated numbers

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

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?

Upvotes: 0

Views: 599

Answers (4)

Yang
Yang

Reputation: 278

just

data = [5, 5, 7, 9, 9, 9, 9, 9]
output = [(x, data.count(x)) for x in set(data)]

print(output)

output:

[(9, 5), (5, 2), (7, 1)]

--

Update:

I think standard for loop will be more proper.

data = [5, 5, 7, 9, 9, 9, 9, 9]
output = []
for x in set(data):
    output.append(x)
    output.append(data.count(x))
    
print(output)

output:

[9, 5, 5, 2, 7, 1]

Upvotes: 0

Alain T.
Alain T.

Reputation: 42143

If you are only looking for repetitions anywhere in the list, then you can use the Counter class from collections which will count the number of each distinct value in the list:

i = [5,5,7,9,9,9,9,9]

from collections import Counter
r = [(c,n) for n,c in Counter(i).items() if c>1]

print(r)
[(2, 5), (5, 9)]

If you want to count streaks of repeating numbers, the the groupby function, from itertools can help by returning groups of consecutive identical values:

i = [5,5,7,9,9,7,7,7,9,9,9]

from itertools import groupby
r = [ (c,n) for n,g in groupby(i) for c in [len([*g])] if c>1]

print(r)
[(2, 5), (2, 9), (3, 7), (3, 9)]

Upvotes: 0

mhhabib
mhhabib

Reputation: 3121

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)}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

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.

Upvotes: 1

Related Questions