因此用戶在一個字串中輸入一個包含 n 個數字的串列(不超過 1000 個),程式會查找并輸出下一個出現概率最高的數字。我有點像初學者,一直堅持計算概率,Python 不會讓我將串列元素和我使用的方法轉換為整數:
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
uj5u.com熱心網友回復:
我想你想要的是:
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)}")
引數 tocollections.Counter應該是您的串列;然后,您可以Counter作為 dict迭代,其中鍵是串列中的專案(用戶輸入的數字),值是每個專案出現的次數。將計數除以串列的總長度告訴您每個專案出現的時間百分比。
1
2
3
2
2
1: 0.2
2: 0.6
3: 0.2
如果你只想得到一個最常出現的數字,max像這樣:
print(f"Most frequent: {max(p, key=p.get)}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387585.html
