Finding the most frequent element in a list excluding a certain character

Question:

I need to run a function that returns the most frequent element in a list except for a certain character, in this case the character "W".

For example, I have a list

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

How would I get an output "2" or 3 instead of "W", which is what statistics.mode(n) is currently giving me?

Any help would be appreciated. Thanks!

Asked By: Enderman

||

Answers:

Try using

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

instead. For furter details on list comprehensions, check out this link.

Answered By: Captain Trojan
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)
Answered By: Indrasena Gangasani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.