Pythonの再帰関数は自動的に巻き戻します

okwaves2024-01-25  392

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

その後、再帰関数が実行されると関数を実行します。関数を返す必要がありますが、巻き戻しで自動的に実行されます。 なぜそうなるのか。

何を言っているのか、またはその関数が何をすることになっているのかわかりませんが、おそらくrec(string, store)の結果に対して何かを行う必要があります。

– tobias_k

2020 年 9 月 3 日 12:05

実際に私は自分のプロジェクトと同じ状況を作成します。したがって、コードに出力(store -- /xxx/xxx/xxx/xxx/xxx)が必要ですが、これだけが得られます - /xxx

– ロケシュ・サフ

2020 年 9 月 3 日 12:09

まだ明確ではありません。おそらく res = rec(...) を実行し、if ブロックで res を返したいと考えていますか?

– tobias_k

2020 年 9 月 3 日 12:13



------------------------

Python の文字列は不変です。 store += f"/{string}" を実行する場合、store に追加するのではなく、実際には、store と f"/{string}" の前のバッファーの連結を含む新しいバッファーを作成します。次に、rec が返された後にスタックをアップすると、store は再帰呼び出しによって変更されていません (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)

1

ご返信いただきありがとうございます。要点はわかりました。本当に助かります。本当にありがとうございました

– ロケシュ・サフ

2020 年 9 月 3 日 12:40

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。