So the user inputs a list of n numbers in one string (not more than 1000), and the program finds and outputs the number with the highest probability of occuring next. I'm somewhat of a beginner and am stuck on counting the prbability, Python won't let me convert both he list element and the method I'm using to ints:
n = [int(input()), int(input()), int(input()), int(input()), int(input())]
for i in n:
P = collections.Counter([i]) / len(n)
print(P) # The program is supposed to determine the highest possibility and print the respective number afterwards
CodePudding user response:
I think what you want is:
import collections
n = [int(input()) for _ in range(5)]
p = collections.Counter(n)
for i, freq in p.items():
print(f"{i}: {freq / len(n)}")
The parameter to collections.Counter
should be your list; you can then iterate over Counter
as a dict where the keys are the items in the list (the numbers entered by the user) and the values are the number of times each item appeared. Dividing the count by the total length of the list tells you the percentage of the time each item appeared.
1
2
3
2
2
1: 0.2
2: 0.6
3: 0.2
If you want to just get the single most frequently appearing number, take the max
like this:
print(f"Most frequent: {max(p, key=p.get)}")