Ruby:
words = %w(louis clark jimmy superman louis)
class Frequency
attr_accessor :words
def initialize(words)
@words = words
end
def letters
hash = Hash.new(0)
# easier to read
# @words.each do |word|
# word.downcase.each_char {|char| hash[char] += 1}
# end
@words.each {|word| word.downcase.each_char {|char| hash[char] += 1}}
hash.sort
end
def words
hash = Hash.new(0)
@words.each {|word| hash[word] += 1}
hash.sort
end
end
freq = Frequency.new(words)
p freq.words
p freq.letters
Python:
words = ['louis','clark', 'jimmy', 'superman', 'louis']
class Frequency(list):
def __init__ (self, value):
self.words_list = value
def letters(self):
dict = {}
for word in self.words_list:
for char in word:
dict[char] = dict.get(char, 0) + 1
return [(k,dict[k]) for k in sorted(dict.keys())]
def words(self):
dict = {}
for word in self.words_list:
dict[word] = dict.get(word, 0) + 1
return [(k,dict[k]) for k in sorted(dict.keys())]
freq = Frequency(words)
print freq.words()
print freq.letters()