【发布时间】:2019-04-03 19:39:44
【问题描述】:
我正在解决一个问题,我正在将单词反转到位。我注意到,根据我在 or 运算符之前和之后的语句顺序,代码将无法正常工作。
如果我改变了
if i == len(s1) or s1[i] == ' ':
到
if s1[i] == ' ' or i == len(s1):
我得到了错误
Traceback (most recent call last):
File "reverse_words_in_place.py", line 58, in <module>
reverse_words(s1)
File "reverse_words_in_place.py", line 6, in reverse_words
if s1[i] == ' ' or i == len(s1):
IndexError: list index out of range
def reverse_words(s1):
reverse_string(s1, 0, len(s1)-1)
start_index = 0
for i in range(len(s1)+1):
if i == len(s1) or s1[i] == ' ':
reverse_string(s1, start_index, i-1)
start_index = i + 1
return s1
def reverse_string(s1, first, last):
while(first < last):
s1[first], s1[last] = s1[last], s1[first]
first += 1
last -= 1
s1 = ['c', 'a', 'k', 'e', ' ',
'p', 'o', 'u', 'n', 'd', ' ',
's', 't', 'e', 'a', 'l']
reverse_words(s1)
# Prints: 'steal pound cake'
print(''.join(s1))
这段代码的输出是
steal pound cake
只要
if i == len(s1) or s1[i] == ' ':
为什么这些语句的顺序很重要?
【问题讨论】: