I'm a newbie in python, and I need to find the most frequent element in list pdInput
and how many elements are the same in the list of mostFreqenNum
mostFreqenNum = []
contMostnum = [0]
ContTraining = int(input('How many time You like to Train you input: '))
for i in range(ContTraining):
pdInput = int(
input('Please input your number whatever you want: '))
mostFreqenNum.append(pdInput)
for x in mostFreqenNum:
coutFreqenNum = contMostnum.count(x)
given a list of values inp
, you can find the most common like this:
using collections.Counter
from collections import Counter
most_common = Counter(inp).most_common(1)
output is a tuple
with (value, count)
inside
using sorted
sorted(inp, key=lambda x: inp.count(x), reverse=True)[0]
output is the most common value in the list
using numpy
: # note only works with numeric values
np.argmax(np.bincount(inp))
output is the most common value in the list
one more using builtins
:
max(set(inp), key=inp.count)
output is the most common value in the list
another using pandas
:
import pandas as pd
pd.value_counts(inp).index[0]
output is the most common value in the list
Why you dont use the built in module from python, statistics. you can use the module like these:
import statistics
### your input code
mode = statistics.mode(mostFreqenNum)
print(mode)
mode() receive parameter list type. Then you can use the count(). Another example, maybe like these:
>>> import statistics
>>> lists = [2,3,2,2,3,4,5]
>>> mode = statistics.mode(lists)
>>> print(mode)
2
>>> lists.count(2)
3
>>>
I am not sure what you are trying to do exactly, but maybe this could work:
mostFreqenNum = {}
contMostnum = 0
myList = [1, 2, 3, 2, 4, 3, 2, 3, 5, 3]
for i in myList:
if i in mostFreqenNum:
mostFreqenNum[i] += 1
else:
mostFreqenNum[i] = 1
for x in mostFreqenNum:
if mostFreqenNum[x] > contMostnum:
contMostnum = mostFreqenNum[x]
mostFreqKey = x
else:
continue
print(f'Most frequent key, {mostFreqKey}, seen {contMostnum} times.')
def Prediction_Model_v3():
alnv3 = [[],[]]
inpv3 = int(input('How many time You like to Train you input V3: '))
for i in range(inpv3):
pdInpv3 = int(
input('V3 input number whatever you want: '))
alnv3[0].append(pdInpv3)
mdv3 = statistics.mode(alnv3[0])
if(pdInpv3 == mdv3):
alnv3[1].append(str(len(alnv3[1])))
print('numberInput V3: ', alnv3[0])
print('Most Frequent number V3 is ', str(mdv3), ':', str(len(alnv3[1])))
pdtISv3 = (((inpv3-int(len(alnv3[1])))*100)/inpv3)
print('Result of prediction V3 is: ', str(
mdv3), '=', str(pdtISv3), '%')
alnv3.clear()
return str(pdtISv3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.