gpt4 book ai didi

ruby-on-rails - 使用 Ruby 计算散列字母的数量?

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:06 25 4
gpt4 key购买 nike

我在计算带有散列的字母时遇到了这个问题:

#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]

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

有更好的方法吗?

最佳答案

你可以通过 -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

关于ruby-on-rails - 使用 Ruby 计算散列字母的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19460428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com