def algae(S, n):
"""
Print S rewritten with the algae rule to recursion depth n
"""
al = {'A': 'AB', 'B': 'A'}
# Base case
if n == 0:
return S
# Transform each symbol in S
for symbol in S:
S += algae(al[symbol], n - 1)
print(algae('A', 5))
嗨,任何人都可以解释为什么在打印此功能的结果时我收到错误:
TypeError: Can't convert 'NoneType' object to str implicitly
这是指第11行(S + =藻类(al [symbol],n - 1))
答案 0 :(得分:3)
当n != 0
时,您的代码会脱离函数的末尾。在Python中,这相当于返回None
。您需要为递归案例添加return
语句。
答案 1 :(得分:3)
修改强>
这是您的脚本的工作版本:
def algae(S, n):
"""
Print S rewritten with the algae rule to recursion depth n
"""
al = {'A': 'AB', 'B': 'A'}
if n == 0:
return S
# Make a new string to build on
mystr = ""
for symbol in S:
# Add the translation to the new string
mystr += al[symbol]
# Recursively call the function, passing in the string
return algae(mystr, n-1)
print(algae('A', 5))
输出:
ABAABABAABAAB
注意:如果你愿意,你可以像@Blckknght那样提高效率:
def algae(S, n):
"""
Print S rewritten with the algae rule to recursion depth n
"""
al = {'A': 'AB', 'B': 'A'}
if n == 0:
return S
mystr = "".join(al[c] for c in S)
return algae(mystr, n-1)
print(algae('A', 5))
答案 2 :(得分:0)
如果n
不为0,则algae
永远不会return
任何内容,因此Python会隐式地为其赋予返回值None
。然后,下一个algae
调用尝试执行S += None
,因为这会产生错误。将return S
添加到函数末尾以解决此问题。
答案 3 :(得分:0)
您在功能结束时缺少“返回S”。
答案 4 :(得分:0)
没有递归的工作版本(从不喜欢递归)
def algae(S, n):
al = {'A': 'AB', 'B': 'A'}
for i in range(n):
newS = ''
for i in range(len(S)):
newS += al[S[i]]
S = newS
return S
print(algae('A', 5))