如何解决python递归函数自动倒带
def s(text):
def rec(string,store):
if len(store) < 20:
store += f"/{string}"
print("store -- ",store)
rec(string,store)
print("store !! ",store)
return store
else:
print("end")
return store
return rec(text,'')
d = s("xxx")
print(d)
输出:-
store -- /xxx
store -- /xxx/xxx
store -- /xxx/xxx/xxx
store -- /xxx/xxx/xxx/xxx
store -- /xxx/xxx/xxx/xxx/xxx
end
store !! /xxx/xxx/xxx/xxx/xxx
store !! /xxx/xxx/xxx/xxx
store !! /xxx/xxx/xxx
store !! /xxx/xxx
store !! /xxx
/xxx
我在递归函数运行后运行该函数,该函数应返回该函数,但它会在倒带时自动运行。 为什么会发生。
解决方法
python中的字符串是不可变的。当您执行store += f"/{string}"
时,您并没有追加到存储区,实际上是在创建一个包含先前存储区和f"/{string}"
的串联的新缓冲区。然后,当您在返回rec
后在堆栈中向上移动时,存储没有被递归调用修改(还要注意,当您在python中调用函数时,会将引用的副本传递给每个参数)。
要获得所需的输出,必须返回store的新值。 (或将商店包装在可变的列表中)
这种方式:
def s(text):
def rec(string,store):
if len(store[0]) < 20:
store[0] += f"/{string}"
print("store -- ",store[0])
rec(string,store)
print("store !! ",store[0])
# No return needed since the list is modified in recursive calls
else:
print("end")
# No return needed either (anyway,it already has its final value...)
store = [''] # <---- Need to create a mutable object to act as a "pointer"(-ish)
rec(text,store)
return store[0] # <---- ...And we return the pointed object. Don't be mistaken,this object is NOT the same as the initial ''. However,the list holding it is the same.
d = s("xxx")
print(d)
或者这样:
def s(text):
def rec(string,store):
if len(store) < 20:
store += f"/{string}"
print("store -- ",store)
store = rec(string,store) # <---- Here I update store with the result of the recursive call
print("store !! ",store)
return store
else:
print("end")
return store
return rec(text,'')
d = s("xxx")
print(d)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。