2014-09-26 80 views
0

我想創建一個程序,其中用戶輸入一個字符串,例如'滾輪',程序將字母轉換爲數字,如a=1, b=2, c=3等,並計算這些值的總和。但是,如果程序在一行中找到兩個相同的字母,那麼它會使總和加倍。到目前爲止,我已經做到了這一點:字母整數

input = raw_input('Write Text: ') 
input = input.lower() 
output = [] 
sum=0 
for character in input: 
    number = ord(character) - 96 
    sum=sum+number 
    output.append(number) 
print sum 

,其計算字符之和還追加字符轉換到一個新的數組。那麼,如果連續出現兩個字母,任何人都可以幫助我將總和翻倍?

+4

你能舉一些例子輸入和輸出像'abbba','aabaa'等 – 2014-09-26 14:24:22

回答

0

存儲前一個字符並將其與當前字符進行比較。如果它們是相同的,則將其值加倍。

word = 'hello' 
out = [] 
c_prev = None 

for c in word: 
    value = ord(c) - ord('a') 

    if c == c_prev: # double if repeated character 
     value = value * 2 

    out.append(value) 
    c_prev = c # store for next comparison 

print(sum(out)) 
+0

奏效感謝名單輸入! – thr 2014-09-27 15:33:41