<p>为了回答您上面的问题,正如@Bhathiya Perera在评论中强调的那样,执行递归调用需要一个退出条件,首先,这样代码不会永远运行,而且还要定义一个令人满意的返回。在</p>
<p>在您的例子中,退出条件是字符串不再包含可以扩展到的重复项,我不能删除更多的字符,或者输入字符串=输出字符串。在</p>
<p>进一步的注释是,如果退出条件定义良好,则可以使用for循环,而不必担心对函数的无休止的调用。在</p>
<pre><code>def remove_adjacent_duplicates(input_string):
'''
Function removes adjacent duplicates recursively
'''
string_length = len(input_string)
# If length of string is 1 or 0 then there are no duplicates present
if string_length == 0 or string_length == 1:
return input_string
# Iterate through the string to remove all duplicates present in first pass
# Note that the range goes from 1 -> len-1 to avoid boundary errors
for i in range(1, string_length - 1):
if input_string[i-1] == input_string[i]:
# Remove duplicates by slicing the string around the duplicates
new_string = input_string[:i - 1] + input_string[i + 1:]
print new_string
if new_string == input_string:
# Define the exit condition
return input_string
else:
# Recursive call if there have been duplicate removals
# This will do a final call to ensure no more duplicates remain
return remove_adjacent_duplicates(new_string)
</code></pre>