如何计算用户输入中字母的频率? [英] How do I count the frequencies of the letters in user input?
本文介绍了如何计算用户输入中字母的频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户输入Ruby中的单词时,如何计算超级加利福尼亚"一词中出现的字母的频率,并打印出星号或星号以计数出现的字母数?
How do I count the frequency of letters that appear in the word "supercaliforniamightly" when the user enters a word like that in Ruby, and print out stars or asterisks to count the number of letters that appear?
这是我的代码:
puts "Enter string: "
text= gets.chomp
text.downcase!
words = text.split(//)
frequencies = Hash.new(0)
words.each{|item| frequencies[item] +=1}
frequencies = frequencies.sort_by{ |item, amount| amount}
frequencies.reverse!
frequencies.each do |item, amount|
puts item + " " + amount.to_s
end
我想要的输出是这样的:
The output I want is something like:
Enter a string:
uuuuiiii
u , 4 ****
i , 4 ****
推荐答案
我稍稍更改了输出(删除了逗号前的空格),以使我看起来没有学问.
I changed the output a little bit (removed the space before the comma) so that I don't look like uneducated.
puts "Enter string: "
gets.chomp.downcase
.each_char.with_object(Hash.new(0)){|c, h| h[c] += 1}
.sort_by{|_, v| v}
.reverse
.each{|k, v| puts k + ", " + v.to_s + " " + "*" * v}
输出:
Enter string:
uuuuiiii
i, 4 ****
u, 4 ****
这篇关于如何计算用户输入中字母的频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文