python random int append to list and count "x" top numbers that occurred and number of times int occurred

542 Views Asked by At

New to python so all help is appreciated! I did check and found several count post but couldn't find any that print the top occurrences from the list. (ie 3 occurred 6x, 4 occurred 4x and 2 occurred 3x)

Goal: I'd like to have the code print 1000 numbers 0,1000 randomly and then be able to choose how many to show.

so for example num = [0,5,12,5, 22,12,0 ,32,22,0,0,5] I want to be able to see say the top 3 repeated numbers and how many times that number occurred. 0-4times, 5-3times, 12-2times.

code Progression #valid attempts are made

Prints 1000 times randomly

import random

for x in range(1001):
    print(random.randint(0,1001))

Append the randint directly to num

import random

num = []
for x in range(1001):
    num.append(random.randint(0,1001))

print(num)

Includes prompt to get how many integers you want to see.

import random

num = []
for x in range(1001):
    num.append(random.randint(0,1001))

highscore = input("Please enter howmany numbers you'd like to see: ")
print("The top", highscore, "repeated numbers are: ", num)

Issues left: how to print highscore's count for num (this part 0-4times, 5-3times, 12-2times.)

Attempt at count issue (prints 0 every time. added num to print to confirm if "y" was in the list)

import random

#creates list
num = []
for x in range(0,10):
    num.append(random.randint(0,10))

highscore = input("input number of reoccurrence's you want to see: ")
y = num.count(highscore)
print(num, y)
2

There are 2 best solutions below

0
Nima Afshar On BEST ANSWER

You can use most_common method from Counter class in collections library. documentation

from collections import Counter
import random

number_of_elements = 1000


counter = Counter([random.randint(0,1001) for i in range(number_of_elements)])


# printing 3 most common elements.
print(counter.most_common(3))

output:

[(131, 6), (600, 5), (354, 5)]

This output means the number 131 is the most common and repeated 6 times, then 600 is the second most common and it is repeated 5 times and so on.

0
hari hara sankar On

It is due to invalid type. Try

y = num.count(int(highscore))

Then it works fine,

input number of reoccurrence's you want to see: 4 [5, 4, 0, 6, 0, 2, 7, 9, 3, 1] 1