大家好!我对Python非常陌生,我正在尝试学习一些基本知识。我在通过初学者在线课程时遇到了一项任务。任务是创建一个程序,它将读取一些字母的字符串,例如“aaabbccc”,并输出“a3b3c3”(另一个示例:它可以是“abccaab”,然后程序将输出“a1b1c2a2b1”)。我想我找到了一种使用while循环来处理它的方法,但最后,当我在if-else中添加elif构造时,它不起作用:当我输入字符串并按enter键时,它只传递到下一行,看起来程序根本没有启动。我将非常感谢任何关于如何修复它的评论或建议,或者任何可能有助于解决任务的替代想法
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
,否则将得到一个无限循环通过使用for循环可以避免这种错误(本质上,它们不太容易出现无限行为) e、 g:
附言: 我想你对最后一个字符有一些逻辑问题
你的问题的答案是“你有一个无限循环”。为什么?
检查代码的这一部分:
正如您所看到的,
if
语句中的块将在j == len(n)-1
时执行,这意味着j
(您正在使用循环通过n
)将到达字符串n
上的最后一个元素。因此,在该行之后j
将保持相同的值,并且不会执行任何其他内容,这意味着条件j < len(n)
将是True
永远,因此你的无限循环。现在,你必须在这里选择:-您可以在该
if
块中添加一个j+=1
-您可以在所有
if
块之外添加j+=1
并将其从其他if
块中移除现在,一些选项存在一些逻辑问题。我将重构您的代码并修复这些问题。此外,我强烈建议您使用有意义的变量名。这将帮助其他人和您(将来)理解和调试您的代码
相关问题 更多 >
编程相关推荐