2014-11-05 119 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)