1

我有这个问题计算带有哈希的字母:

#Counting with hashes!
#Experiment by writing a couple of short programs that will use Hashes to count 
#objects by incrementing a key value.
#Write a funcition that will count the number of letters in a phrase.
#Example "cat in the hat"  -> return:  {"t"=>3, "h"=>2, "a"=>2, "i"=>1, "n"=>1, "e"=>1, "c"=>1}
#From descending order.  Largest to smallest.  Do not include spaces.

这是我的解决方案:

def count_letters(str)
  count = Hash.new(0)
  str.delete(" ").each_char { |letter|  count[letter]+=1}  
  Hash[count.sort_by {|k,v| v}.reverse]
end

print count_letters("cat in the hat")

为了让我按降序对其进行排序,我不得不输入这段代码:

Hash[count.sort_by {|k,v| v}.reverse]

我还能做哪些折射?还有其他方法可以进行降序排序吗?

有没有更好的方法来做到这一点?

4

3 回答 3

3

您可以通过排序来避免相反的情况-v

def count_letters(str)
  counts = str.delete(' ').each_char.inject(Hash.new(0)) {|a,c| a[c] += 1; a}
  Hash[counts.sort_by {|_,v| -v}]
end
于 2013-10-18T23:29:12.093 回答
2

通常我们会这样做:

def count_letters(s)
  Hash[s.delete(' ').split('').group_by{ |c| c }.map{ |k, v| [k, v.size] }]
end

print count_letters("cat in the hat")
# >> {"c"=>1, "a"=>2, "t"=>3, "i"=>1, "n"=>1, "h"=>2, "e"=>1}

然后很容易对其进行排序:

def count_letters(s)
  Hash[
    s.delete(' ')
     .split('')
     .group_by{ |c| c }
     .map{ |k, v| [k, v.size] }
     .sort_by{ |k, v| [-v, k] }
  ]
end

print count_letters("cat in the hat")
# >> {"t"=>3, "a"=>2, "h"=>2, "c"=>1, "e"=>1, "i"=>1, "n"=>1}

结果排序按计数降序,当计数相同时按字符升序。

我正在对方法进行排序,但对于实际工作,除非需要,否则我不会进行排序,然后我只会在需要排序的地方进行排序。对每个哈希都这样做是一种浪费,因为它不会加速值的检索。


从运行基准测试中,我们知道使用-v不是反转排序顺序的最佳方式。它实际上使用起来更快v,然后附加reverse到结果数组。

于 2013-10-18T23:35:51.590 回答
2

解决方案:

 def  letter_count(word)
    hash = {}
    hash.default = 0 
    letters = word.downcase.chars
    letters.each do |letter| 
        hash[letter] +=1
  end
  p hash
end

回答:

letter_count("I love you")
{"i"=>1, "l"=>1, "o"=>2, "v"=>1, "e"=>1, "y"=>1, "u"=>1}
于 2015-05-21T19:04:18.900 回答