我正在做一个字符串重写函数,它接受一个字符串并根据字典中的规则重写它。代码只运行一次就可以了,但我需要它调用自己n次,并打印“nth”重写的字符串。我需要递归的代码是:S = "AB"
def srs_print(S, n, rules):
'''
A function that takes a dictionary as SRS rules and prints
the output
'''
axiom = list(S)
key = []
value = []
output = ''
for k in rules:
#Inputs the keys of the rules dictionary into a new list
key.append(k)
#Inputs the value of the rules dictionary into a new list
value.append(rules[k])
for x in axiom:
if x in key:
axiomindex = key.index(x)
output += value[axiomindex]
else:
output += x
S = output
return S
#j = srs_print(S, 5, {'A':'AB', 'B': 'A'})
#print(j)
#while len(range(n)) > 0:
# S = srs_print(S, n, rules)
# n = n-1
#print("The", n, "th rewrite is " )
#j = srs_print(S, 5, {'A':'AB', 'B': 'A'})
print(srs_print("A", 5, {'A':'AB', 'B': 'A'}))
这会将“A”变成“AB”,但我需要它将'S'放回函数中,然后再次运行'n'次。如您所见,一些注释代码是我尝试使用但失败的行。在
我希望我已经解释清楚了。在