我有这个问题用哈希计算字母:
#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]
我还能做什么折射?还有另一种方法可以进行降序排序吗?
有更好的方法吗?
答案 0 :(得分:2)
您可以按-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
答案 1 :(得分: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}
结果排序按计数递减,当计数相同时按字符递增。
我正在对方法进行排序,但对于实际工作,除非我需要,否则我不会进行排序,然后我只会在需要排序的地方进行。为每个哈希做这件事都是浪费,因为它不会加快对值的检索。
从运行基准测试中,我们知道using -v
isn't the best way to reverse the sort order。使用v
然后将reverse
附加到生成的数组实际上会更快。
答案 2 :(得分:1)
解决方案:
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}