python递归函数自动倒带

python递归函数自动倒带,python,function,Python,Function,我在递归函数运行时运行该函数,之后它应该返回该函数,但它会在倒带时自动运行。 为什么会这样。python中的字符串是不可变的。当您执行store+=f/{string}“操作时,您并不是附加到store,而是在创建一个新的缓冲区,其中包含store和f/{string}”的前一个缓冲区的串联。然后,当您在返回rec后重新启动堆栈时,存储区没有被递归调用修改(还要注意,当您在python中调用函数时,您将引用的副本传递给每个参数) 要获得所需的输出,必须返回store的新值。(或在可变列表中包装存

我在递归函数运行时运行该函数,之后它应该返回该函数,但它会在倒带时自动运行。
为什么会这样。python中的字符串是不可变的。当您执行
store+=f/{string}“
操作时,您并不是附加到store,而是在创建一个新的缓冲区,其中包含store和
f/{string}”的前一个缓冲区的串联。然后,当您在返回
rec
后重新启动堆栈时,存储区没有被递归调用修改(还要注意,当您在python中调用函数时,您将引用的副本传递给每个参数)

要获得所需的输出,必须返回store的新值。(或在可变列表中包装存储)

这样:

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
defs(文本):
def rec(字符串、存储):
如果len(存储[0])<20:
存储[0]+=f/{string}”
打印(“存储--”,存储[0])
记录(字符串、存储)
打印(“存储!!”,存储[0])
#由于在递归调用中修改了列表,因此不需要返回
其他:
打印(“结束”)
#也不需要返回(无论如何,它已经有了最终值…)

store=['']#不确定你的意思是什么,或者该函数应该做什么,但是你可能应该对
rec(string,store)
的结果做些什么。实际上,我创建了我在项目中遇到的情况。所以我需要代码中的输出(存储--/xxx/xxx/xxx/xxx/xxx),但它只给出了这个-/xxx,直到不清楚为止。也许你想要
res=rec(…)
,然后
if
块中返回res
?谢谢你的回复。我明白了,这对我很有帮助。多谢各位
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
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)