2014-11-05 406 views
-3

我想用Python解決'Love-Letter' mystery problem of HackerRank,但我被困在一個地方,在我的循環中一個變量沒有得到更新。Python - 變量不在循環中更新

s = input() 
first_char = s[0] 
last_char = s[-1] 
ascii_first_char = ord(first_char) 
ascii_last_char = ord(last_char) 
count = 0 
i = 1 
while ascii_first_char < ascii_last_char: 
    count += abs((ascii_last_char-ascii_first_char)) 
    ascii_first_char = ord(s[i]) 
    ascii_last_char = ord(s[-i]) 
    i += 1 

print(count) 

如果您嘗試運行,你會看到ALC沒有改變它根據ord(s[i]),我不斷遞增的價值。爲什麼會發生?

+1

這是您的實際代碼?行'alc = ord(s [-i)])'具有不匹配的圓括號,因此它應該與SyntaxError一起崩潰。 – Kevin 2014-11-05 18:52:17

+0

是的,我修好了,現在呢? – 2014-11-05 18:58:30

+1

你應該給你的變量更多說話的名字。這是一個局外人很難讀... – 2014-11-05 19:00:48

回答

1

你得到第一個字母s [0],最後一個s [-1]。在你的循環中,你將採用下一個具有相同索引i的字母。

我不明白你的條件在while循環中。而不是「ascii_first_char < ascii_last_char」,你應該測試你是否查看了字符串的每一個元素。爲此,我們必須循環len(s)/ 2次。喜歡的東西:

while i < len(s) - i: 

或同等

while 2*i < len(s): 

而這種情況只是甚至長度工作。我更喜歡for循環,當我知道有多少次我將環

current_line = input() 
# if length is even, we don't care about the letter in the middle 
# abcde <-- just need to look for first and last 2 values 
# 5 // 2 == 2 
half_length = len(current_line) // 2 
changes = 0 
for i in range(index): 
    changes += abs(
     ord(current_line[i]) - ord(current_line[-(i+1)]) 
    ) 
print (changes) 
0
s1 = ['abc','abcba','abcd','cba'] 
for s in s1: 
    count = 0 
    i = 0 
    j = -1 
    median = len(s)/2 
    if median == 1: 
     count += abs(ord(s[0])-ord(s[-1])) 
    else: 
     while i < len(s)/2: 
      count += abs(ord(s[j])-ord(s[i])) 
      i += 1 
      j -= 1 
    print(count)