Skip to content Skip to sidebar Skip to footer

Find Duplicate Elements In A List

I have a lists: nums = [1, 2, 3, 1, 5, 2, 7, 11] I am trying to make a function that returns how many times each number appears in the lists. Output may look like: 1 occurred 2 ti

Solution 1:

Counter is all you need

>>>from collections import Counter>>>Counter([1, 2, 3, 1, 5, 2, 7, 11])
Counter({1: 2, 2: 2, 3: 1, 5: 1, 7: 1, 11: 1})

Or you can just fix your code like this

def main():
    original_nums = input("Enter integers between 1 and 100: ")
    nums = [i for i in original_nums.split()]
    my_dict = {}

    for i in nums:
        my_dict[i] = my_dict.get(i, 0) + 1
        # or .setdefault(i, 0) instead of .get(i, 0)
        # setdefault is generally faster

    for i in my_dict:
        print(i, 'occurs', my_dict[i], 'times')

if __name__ == '__main__':
    main()

Runtime:

Enter integers between 1 and 100: 5 5 5 5 1 2 3 3 3 
1 occurs 1 times
2 occurs 1 times
3 occurs 3 times
5 occurs 4 times

Solution 2:

You can simply use a collections.Counter, which essentially does what you're trying to do internally:

>>>from collections import Counter>>>>>>nums = [1, 2, 3, 1, 5, 2, 7, 11]>>>>>>counts = Counter(nums)>>>>>>for t in counts.iteritems():...print'%d occured %d times' % t... 
1 occured 2 times
2 occured 2 times
3 occured 1 times
5 occured 1 times
7 occured 1 times
11 occured 1 times

Post a Comment for "Find Duplicate Elements In A List"