2012-03-27 73 views
0

在給定字典中,每個鍵都是單個小寫字母,每個值都是以該字母開頭的小寫字母的數量。 str參數是一個小寫字母。根據字典中的值,返回以該字母開頭的單詞的百分比。獲取python字典中字母的百分比

注意:使用浮點除法。

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) #?? 
+1

這是功課? – jgritty 2012-03-27 15:31:13

回答

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) 
+0

剛剛意識到我需要返回一個浮點數,這樣我纔會擺脫打印語句 – Who8daPie 2012-03-27 15:50:25

0

如果每個值是每個字母的單詞數,那麼你的代碼中查找的總和將是:

sum = 0 
for (key, value) in dictionary: 
    sum = sum + value 

然後,它的情況:

def get_letter_percentage(dictionary, letter): 
    return dictionary[letter]/sum 
+0

感謝您的幫助 – Who8daPie 2012-03-27 15:45:33

1
def get_letter_percentage(dictionary, s): 
    '''(dict of {str : int}, str) -> float''' 

    return dictionary[s] * 1.0/sum(dictionary.values()) 

百分比是出現次數除以總出現次數。 注意乘以1.0以避免int分割。

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") 
+0

感謝您的迴應! – Who8daPie 2012-03-27 15:45:00

0
def get_letter_percentage(stats, letter): 
    return stats[letter]/(sum(stats.values()) + 0.0)