Home > database >  Finding the most frequent element in a list excluding a certain character
Finding the most frequent element in a list excluding a certain character

Time:06-13

I need to run a function that returns the most frequent element in a list except for the character "W". For example if I have a list n = ['W', 3, 'W', 1, 'W', 3, 2, 2, 3, 2], how would I get an output "2" instead of "W", which is currently what I get when running statistics.mode() on that list? Any help would be appreciated. Thanks!

CodePudding user response:

Try using

statistics.mode([v for v in n if v != 'W'])

instead.

CodePudding user response:

thisdict = { }

n = ["W", 3, "W", 1, "W", 3, 2, 2, 3, 2]

for i in n:

if i in thisdict.keys():

thisdict[i] = thisdict[i]   1

else:

if (i == "W"):
  continue

thisdict[i] =  1

max = 0 maxKey = None

for key in thisdict.keys():

if( thisdict[key] >= max ):

max = thisdict[key]

maxKey = key

print("Element Occurred Max Number of Times-->", maxKey)

  • Related