我已经写了上面的程序。如果str中有chr,并且字符follow chr与chr不同,程序应该从str中删除chr。在
有谁能帮我一下这是怎么回事?为什么工作不正常?我看到函数内部的函数调用有一些问题。在
def removesingleton(str,chr):
'''
(str,str)->(str)
Returns str with removed single chr
>>>removesingleton("Welcomee","e")
Wlcomee
>>>removesingleton("XabXXaX","X")
abXXa
'''
output, index = "", 0
if str:
for char in str:
if char == chr:
if index+1 < len(str) and str[index+1] == chr:
output += str[:index+2]
removesingleton(str[index+2:],chr)
else:
removesingleton(str[index+1:],chr)
else:
output += str[index]
removesingleton(str[index+1:],chr)
index += 1
return output
print removesingleton("XabXXaX","X")
你不需要任何递归调用。它们是完全不必要的,因为您在单个调用中对整个字符串执行循环。(您还忽略了返回值,因此递归一开始没有多大意义。)
您需要检查下一个字符和前一个字符,看看当前字符是否是重复序列的一部分。您不需要执行任何切片,甚至不需要显式循环。下面是代码的工作版本,在
str.join
调用中被提炼为一个生成器表达式:相关问题 更多 >
编程相关推荐