[英]additional if condition (elif) doesn't work in while loop
大家。 我对 Python 很陌生,我正在尝试学习一些基本知识。 我在为初学者通过在线课程时遇到了一个任务,该任务是创建一个程序,它会读取一些字母的字符串,例如'aaabbbccc':和output'a3b3c3'(另一个例子,它可能是'abccaab '。那么程序应该 output 'a1b1c2a2b1'),我想我找到了一种使用 while 循环处理它的方法,但最后,当我在 if else 中添加 elif 构造时:它不起作用,当我输入我的字符串并按回车。 它只是传递到下一行,似乎程序还没有开始。 对于如何修复它或任何有助于解决任务的替代想法,我将非常感谢任何评论或建议。
n = input()
i = 0
j = i + 1
s = 1
m = ''
while j < len(n):
if j == len(n) - 1:
s += 1
m += n[j] + str(s)
elif n[i] != n[j]:
m += n[i] + str(s)
i += 1
j += 1
s = 1
else:
i += 1
j += 1
s += 1
print(m)
你需要总是增加j
否则你会得到一个无限循环
while j < len(n):
if j == len(n) - 1:
s += 1
m += n[j] + str(s)
elif n[i] != n[j]:
m += n[i] + str(s)
i += 1
s = 1
else:
i += 1
s += 1
j += 1
您可以通过使用 for 循环来避免这种错误(本质上它们不太容易出现无限行为),例如:
s = 1
m = ''
for i in range(len(n) - 1):
j = i + 1
if j == len(n) - 1:
s += 1
m += n[j] + str(s)
elif n[i] != n[j]:
m += n[i] + str(s)
s = 1
else:
s += 1
print(m)
ps:我认为您对最后一个字符有一些逻辑问题
s = 1
m = ''
for i in range(len(n)):
j = i + 1
# handle last char
if j >= len(n):
if s > 1:
# If the last char is the same as previous one
m += n[i] + str(s)
else:
# if the last char is different
m += n[i] + str(s)
elif n[i] != n[j]:
m += n[i] + str(s)
s = 1
else:
s += 1
好吧,你的问题的答案是“你有一个无限循环”。 为什么?
检查这部分代码:
if j == len(n) - 1:
s += 1
m += n[j] + str(s)
如您所见, if
语句中的该块将在j == len(n)-1
时执行,这意味着j
(您用于循环n
将到达字符串n
上的最后一个元素。因此,在那行之后j
将保持相同的值,并且不会执行任何其他操作,这意味着条件j < len(n)
将永远为True
,因此您的无限循环。现在,您必须在这里选择:
-您可以在if
块内添加j+=1
。
if j == len(n) - 1:
s += 1
m += n[j] + str(s)
j += 1
-您可以在所有if
块之外添加j+=1
并将其从其他if
块中删除
while j < len(n):
if j == len(n) - 1:
s += 1
m += n[j] + str(s)
elif n[i] != n[j]:
m += n[i] + str(s)
i += 1
s = 1
else:
i += 1
s += 1
j += 1
现在,一些选项存在一些逻辑问题。 我将重构您的代码并解决问题。 另外,我强烈建议您使用有意义的变量名。 它将帮助其他人和您(将来)理解和调试您的代码。
word = input()
result = "" # This will hold the result string
# Will assume user did not input an empty string. You could check that though
currentLetter = word[0] # Get the first letter
currentCount = 1 # Count it as 1
j = 1 # To start from the index 1 and iterate over word letters
while(j < len(word)):
if word[j] != currentLetter:
# if the letter on the current index is different from the currentLetter
# means there was a change so we must add to the result string what
# we counted (letter and count)
result += currentLetter + str(currentCount)
# Get the new letter and set its count to 1
currentLetter = word[j]
currentCount = 1
else:
# Else the letter is the same so far -> increase count
currentCount += 1
j += 1 # Increase index variable
else:
# This else will execute when the while condition is false
# add the remaining values
result += currentLetter + str(currentCount)
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.