Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Write a function named `freq(l)` that takes a list `l` of numbers
and returns a tuple of the most frequent number and its frequency.
For example, `freq([1,2,3,4,5,2,3,4,5,3,4,5,4,5,4]) returns (4,5)
because number 4 appears 5 times in this list. If multiple numbers
appear as most frequent, then the first element of the returned
tuple is a list of all those numbers. For example,

freq([1,2,3,1,2,1,2,3,1,2]) will return ([1,2], 4) because both
1 and 2 appear 4 times in the list.


How can i solve this in Python.

What I have tried:

I do'not not have idea regarding this..
Posted
Updated 23-Mar-22 5:38am

Not exactly what you need, but close to.
Python
def freq(l):
  s = { x for x in l } # a set: get the unique values 
  lt = [ (x, l.count(x)) for x in s ] # list of tuple containing unique values and their occurrences in the list
  mv = max(lt,key=lambda item:item[1])[1] # the maximum number of occurrences
  r = ([ x for (x,v) in lt if v == mv], mv) # the resulting tuple, filtering out all the items with less occurrences than the maximum
  return r
 
Share this answer
 
 
Share this answer
 
Quote:
I do'not not have idea regarding this..

The first idea is "How do I solve it by hand ?"
Then "Can I apply the 'by hand' solution to programming ?"
In short, you can't just have no idea.

In case you really have no idea for such a simple thing, you need to talk with your teacher.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900