422,734 Members | 1,336 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 422,734 IT Pros & Developers. It's quick & easy.

Indicate what integer element appears the most in a list

P: 1
list = [1,5,3,6,22,45,63,30,344,22,12,25,10]
I have to print the element that appears the most in my list. In this case it will be the 22.

I need some help understand where i begin.

Thanks
Nov 28 '17 #1
Share this Question
Share on Google+
3 Replies


numberwhun
Expert Mod 2.5K+
P: 3,503
Once could use a dictionary for this. Use the value of each element in the list as the key and the count as the number for each. For each, check if its in the dictionary. If not, add it and set the value to 1. If it exists, increment the value by 1. Grab the one with the highest count.
Dec 5 '17 #2

Expert 100+
P: 921
Ok, I am new to python, but 30 minutes worth trying I got this:

Expand|Select|Wrap|Line Numbers
  1. del a
  2. a = {}
  3. list = [1,5,3,6,22,45,63,30,344,22,12,25,10] 
  4. m = 0
  5.  
  6. for i in list:
  7.     if str(i) in a:
  8.         a[str(i)] = a[str(i)]+1
  9.     else:
  10.         a[str(i)] = 1
  11.     print i, a[str(i)]
  12.  
  13. for i in a:
  14.     print a[i], i, m
  15.     if a[i]>m:
  16.        m=a[i]
  17.        k=i
  18.  
  19. print k
  20.  
which leaves enough room for improvement... ;)
Dec 6 '17 #3

Frinavale
Expert Mod 5K+
P: 9,731
You could always refer to the python documentation for Python Data Structures for more information on structures like a Dictionary as numberwhun suggested ;)

That link to the documentation gives a very good example of how to use Dictionaries to accomplish what you are trying to do.
Dec 6 '17 #4

Post your reply

Sign in to post your reply or Sign up for a free account.