2

I'm new to Python and I'm stuck trying to figure out how to count how many times a number shows up in a list. The output I'm looking for is something like this "7 occurred 2 times, 4 occurred 1 time" but the problem I'm running into is that I'm printing output for each my_integer. So if I enter 7, 7, 4 as input I get "7 occurred 2 times, 7 occurred 2 times, 4 occurred 1 time" I was thinking of writing a method to check for uniqueness of a number after count has been returned.

integers = input("Enter integers between 1 and 100: ")
split_integers = integers.split()
integer_list = [eval(x) for x in split_integers]

for my_integer in integer_list:
    print(integer_list.count(my_integer))
2
  • 4
    there is a counter in python, which you can use.pymotw.com/2/collections/counter.html Commented Jan 29, 2018 at 3:35
  • Use a dictionary. Commented Jan 29, 2018 at 3:41

5 Answers 5

5

Firstly, you don't need to use eval() in this line:

 integer_list = [eval(x) for x in split_integers]

you can simply cast int() here.

Furthermore, since your just counting numbers, you don't even need to convert them to integers to begin with. The conversion would only be necessary if you needed to do some computation with these integers, but since your just counting unique ones, keeping them as strings works fine here.

Secondly, if you want to count unique items, you can use collections.Counter() for this:

from collections import Counter

integers = input("Enter integers between 1 and 100: ")
split_integers = integers.split()

counts = Counter(split_integers)
for k, v in counts.items():
    print(k, 'occurred', v, 'times')

Which works as follows:

Enter integers between 1 and 100: 7 7 4 7 4
7 occurred 3 times
4 occurred 2 times

Counter() is basically a subclass of dict for counting objects. It stores elements in a dictionary where the elements are stored as keys and their counts as values. This allows you to count unique items and store how many times they occur.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not even sure that the call to int is necessary for this.
@SethMMorton Yeah your right, keeping them as strings to begin with work just as fine. I'll update it, cheers.
2

You can use set().

for my_integer in set(integer_list):
    count = integer_list.count(my_integer)
    tmp = "{} occurred {} time".format(my_integer, count)
    if count > 1:
        tmp += "s"
    print(tmp)

For integer_list = [7, 7, 4], it should print out

4 occurred 1 time
7 occurred 2 times

Why does it print the number 4 first before 7? Because set() automatically sorts the array. Learn more about it here.

Comments

2

You can use itertools.groupby to generate a dict of element and number of times it appears in the list. The input list to groupby should be sorted(either in ascending or descending).

>>> from itertools import groupby
>>> l = [1,2,2,1,3,3,3,3,4,5,6,6,6]
>>> {k:len(list(v)) for k,v in groupby(sorted(l))}

This will output

>>> {1: 2, 2: 2, 3: 4, 4: 1, 5: 1, 6: 3}

Or you can use list comprehension to produce a list of tuples and then pass it to dict constructor. This will also yield same result

>>> dict((k,len(list(v))) for k,v in groupby(sorted(l)))
>>> {1: 2, 2: 2, 3: 4, 4: 1, 5: 1, 6: 3}

Comments

1

You can use a dictionary:

integers = input("Enter integers between 1 and 100: ")
split_integers = integers.split()
integer_list = [eval(x) for x in split_integers]

counts = {}
for my_integer in integer_list:
    try:
        counts[my_integer] += 1
    except KeyError:
        counts[my_integer] = 1

for k in counts:
    print('Integer {} occurred {} times'.format(k, counts[k]))

Comments

0

No module imports:

b = []                               #addition 1
for my_integer in integer_list:
    if my_integer in b:
        print (value, "occurs", integer_list.count(my_integer))
        b.append(my_integer)

or

while len(a) > 0:
   value = a[0]
   count = a.count(value)
   print (value, "occurs", count)
   for i in range(count):
      a.remove(value)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.