Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to find the number with the highest probability of being the next one in a user input list?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading