在给定的字典中,每个键都是一个小写字母,每个值都是以该字母开头的小写字母数。 str参数是一个小写字母。根据字典中的值,返回以该字母开头的单词的百分比。
注意:使用浮点除法。
def get_letter_percentage(dictionary, s):
'''(dict of {str : int}, str) -> float'''
# Start with a counter for the sum of the values.
count = 0
# And then look at the key and value of the dictionary
for (key, value) in dictionary.items():
这是我被卡住的地方。我知道我需要创建一个值的总和,以便进行浮点除法。
# guessing it is something along these lines
count = len(values) #??
答案 0 :(得分:3)
也许你可以在你的功能中尝试这样的事情:
dictionary = {'a': 5, 'b': 8, 'c':15}
sum = 0
for (key, value) in dictionary.items(): sum += value
percentage = dictionary['a'] / (sum + 0.0)
print "percentage of '%s' is %.2f %%" % ('a' , percentage*100)
答案 1 :(得分:1)
def get_letter_percentage(dictionary, s):
'''(dict of {str : int}, str) -> float'''
return dictionary[s] * 1.0 / sum(dictionary.values())
百分比是出现次数除以总出现次数。 注意乘以1.0以避免int除。
答案 2 :(得分:0)
如果每个值都是每个字母的单词数,那么找到总和的代码将是:
sum = 0
for (key, value) in dictionary:
sum = sum + value
然后是一个案例:
def get_letter_percentage(dictionary, letter):
return dictionary[letter] / sum
答案 3 :(得分:0)
我想出了这个:
mydict = {"a":5, "b":1, "c":4, "d":3, "e":6}
def get_letter_percentage(dictionary, s):
sum = 0
for key in dictionary:
sum += dictionary[key]
return float(dictionary[s]) / float(sum)
print get_letter_percentage(mydict, "b")
答案 4 :(得分:-1)
def get_letter_percentage(stats, letter):
return stats[letter] / (sum(stats.values()) + 0.0)