我有一个可能的清单,将以这样的形式提供给我:
['A', '-', 'A', 'a', '-', '-','-','a','A','-','-']
使用递归,我需要填充相似元素之间的空格,或者像这样在列表列表的末尾填充空格:
['A', 'A', 'A', 'a', 'a', 'a','a','a','A','A','A']
我能够做到这一点而无需递归,但是我对如何递归执行此操作感到困惑。任何帮助将不胜感激!
[您需要做的就是检查'-'
中是否存在list
,如果是,则用相邻元素替换单个'-'
,然后再次递归,如果不是,则返回list
。
lst = ['A', '-', 'A', 'a', '-', '-','-','a','A','-','-']
def recur(lst):
if '-' in lst:
for i, j in enumerate(lst):
if j == '-':
try:
lst[i] = lst[i-1]
except IndexError:
lst[i] = lst[i+1]
return recur(lst)
else: return lst
print(recur(lst))
或,无循环:
def recur(lst):
if '-' in lst:
i = lst.index('-')
try:
lst[i] = lst[i-1]
except IndexError:
lst[i] = lst[i+1]
return recur(lst)
else: return lst
编辑:如果序列以两个-
开头,则上述方法将超过最大递归深度。在这种情况下,您可以执行以下操作:
def recur(lst):
if '-' in lst:
for i, j in enumerate(lst):
if j == '-':
try:
lst[i] = lst[i-1]
except IndexError:
lst[i] = lst[i+1]
if lst[i] != '-': return recur(lst)
else: return lst
输出:
['A', 'A', 'A', 'a', 'a', 'a', 'a', 'a', 'A', 'A', 'A']
def rec(_list, currentIndex, prevChar):
if currentIndex == len(_list): # End of list
return
if _list[currentIndex]=='-': # If current character is '-', replace it with previous character
_list[currentIndex] = prevChar
rec(_list,currentIndex+1,_list[currentIndex]) # Recurse for rest of the list
_list1 = ['A', '-', 'A', 'a', '-', '-','-','a','A','-','-']
_list2 = ['-', 'A', '-',]
# Assuming initial `prevChar` is 'A' for cases when list starts directly with '-' characters. Ex ['-','A','-']
rec(_list1,0,'A')
rec(_list2,0,'A')
print(_list1)
print(_list2)