2012-03-27 7 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

答えて

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

0

、そして合計を見つけるためにあなたのコードは次のようになります。そして、

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

それはの場合です:たぶん

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

助けをありがとう – Who8daPie

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

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

パーセントは、発生の合計を合計発生数で割ったものです。 int除算を避けるため1.0の乗算に注意してください。

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

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