Mode


#1

I bet there’s a more elegant way to write this. Anyone want to show me?

def mode(li)
best_num = nil
best_count = -1
li.uniq.each do |item|
count = (li.select { |item2| item == item2}).length
if count > best_count
best_count = count
best_num = item
end
end
best_num
end

– Elliot T.


#2

On 6/5/06, Elliot T. removed_email_address@domain.invalid wrote:

 end

li.uniq.collect {|i| [li.select {|j| j == i}.size, i]}.sort.last.last


#3

-----Original Message-----
From: Elliot T. [mailto:removed_email_address@domain.invalid]

I bet there’s a more elegant way to write this. Anyone want
to show me?

def mode(li)

end

It would probably help if you said what you were trying to achieve
rather than asking people to try and interpret code that you admit isn’t
elegant.

class Array
def mode
count = Hash.new(0)
each {|x| count[x] += 1 }
count.sort_by{|k,v|v}.last[0]
end
end


#4

On Jun 4, 2006, at 11:31 PM, Alder G. wrote:

li.uniq.collect {|i| [li.select {|j| j == i}.size, i]}.sort.last.last

cool, thanks, collecting pairs works well.

On Jun 4, 2006, at 11:40 PM, Daniel S. wrote:

It would probably help if you said what you were trying to achieve
rather than asking people to try and interpret code that you admit
isn’t
elegant.

Mode means:

(Statistics) the value that occurs most frequently in a given set of
data.

class Array
def mode
count = Hash.new(0)
each {|x| count[x] += 1 }
count.sort_by{|k,v|v}.last[0]
end
end

that’s a nice way :slight_smile:

– Elliot T.


#5

Hi Micheal,

I could not get your example to work properly. It seemed to return the
count of the highest number in my initial list.

I modified it to

li.inject(Hash.new(0)){|s,v| s[v] += 1; s}.invert.max.last

and it gave me the result I expected. Is it just me tho?


#6

li.inject(Hash.new(0)){|s,v| s[v] += 1; s}.max.last


#7

count of the highest number in my initial list.

I modified it to

li.inject(Hash.new(0)){|s,v| s[v] += 1; s}.invert.max.last

and it gave me the result I expected. Is it just me tho?

another one:

li.sort_by{|x| li.select{|y| x==y}.length}.last

cheers

Simon


#8

another one:

li.sort_by{|x| li.select{|y| x==y}.length}.last

even better (if === does what you expect)

li.sort_by{|x|li.grep(x).size}.last


#9

Hi,

“Kroeger, Simon (ext)” removed_email_address@domain.invalid writes:

li.sort_by{|x|li.grep(x).size}.last

In 1.9, you can use Enumerable#max_by.

li.max_by{|x|li.grep(x).size}