-1

So I have to find the occurrences of each number in a list that the user is prompted to enter (numbers between 1 and 100), my idea was to count each number and then print it out if it occurs at all, and if it doesn't occur, do nothing. Any ideas to go off of this?

il1 = eval(input("Enter integers between 1 and 100 "))

lst1 = []



for i in range(0,len(il1)):
    lst1.append(il1[i])

for i in range(0,len(lst1)):
    for j in range(1,100+1):
        if lst1.count([j]) != 0:
            print(i,"occurs",lst1.count[j],"times")
        else:
            continue
trent
  • 25,033
  • 7
  • 51
  • 90
  • Why use `eval`? `why are you calling `count()` with `j` encased in a list? why are you trying to access `count` with index `j`? perhaps look into [Counter from the collection module](https://docs.python.org/3/library/collections.html#collections.Counter) – MooingRawr Nov 24 '17 at 19:53
  • You code python like java, you can do this in python with one line – user1767754 Nov 24 '17 at 19:54
  • 3
    Possible duplicate of [How to count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-to-count-the-occurrences-of-a-list-item) – trent Nov 24 '17 at 20:03

2 Answers2

0

In python you do :

yourNum = 5
[1,2,3,4,5,5].count(yourNum)
> 2
user1767754
  • 23,311
  • 18
  • 141
  • 164
0

Edit: As the usage of eval is considered to be bad practice, I suggest parsing numbers via a regex. Other options with other properties are also possible.

import re

LIMITS = (1, 100)

line = input("Enter integers between %d and %d: " % LIMITS)

# parse input for all possible numbers
numbers = [int(digits) for digits in re.findall(r'[0-9]+', line)]

# filter for valid numbers in given range
numbers = [n for n in numbers if LIMITS[0] <= n <= LIMITS[1]]

# count occurences; save in dict for easy use later
occurences = {}
for number in numbers:
    if number in occurences:
        occurences[number] += 1
    else:
        occurences[number] = 1

print(occurences)

Yes, this could be squeezed into one line. But for readability, you shouldn't. :-)

creativecoding
  • 247
  • 2
  • 9