すべての反復中に再帰はどのように発生しますか?self.f2(curr、s1 [1:])+ self.f2(curr + [s1 [0]]、s1 [1:])の意味は何ですか
class Subset:
def f1(self, s1):
return self.f2([], sorted(s1))
def f2(self, curr, s1):
if s1:
return self.f2(curr, s1[1:])+ self.f2(curr + [s1[0]], s1[1:])
return [curr]
a=[]
n=int(input("Enter number of elements of list: "))
for i in range(0,n):
b=int(input("Enter element: "))
a.append(b)
print("Subsets: ")
print (Subset().f1(a))
コードを少し単純化してみましょう。ここで作業を行うコア関数は次のとおりです。
def f2(cur, s):
if s:
return f2(cur, s[1:])+ f2(cur + [s[0]], s[1:])
return [cur]
f2([], [1, 3, 2])
# res = [[], [2], [3], [3, 2], [1], [1, 2], [1, 3], [1, 3, 2]]
それでは、プロセス全体を段階的に見ていきましょう。
f2([], [1, 3, 2])
= return([], [3, 2]) + return([1], [3, 2])
# expanding the returns respectively
= return([], [2]) + return([3], [2]) + # first return
return([1], [2]) + return([1, 3], [2]) # second return
# ok, again I will expand these returns in the next line
= return([], []) + return([2], []) + # first return
return([3], []) + return([3, 2], []) + # second return
return([1], []) + return([1, 2], []) + # thir return
return([1, 3], []) + return([1, 3, 2], []) # fourth return
now since all of the seconds lists are empty, the result starts to unfold,
return([], []) = []
return([2], []) = [2]
return([3], []) = [3]
return([3, 2], []) = [3, 2]
return([1], []) = [1]
return([1, 2], []) = [1, 2]
return([1, 3], []) = [1, 3]
return([1, 3, 2], []) = [1, 3, 2]
res = [[], [2], [3], [3, 2], [1], [1, 2], [1, 3], [1, 3, 2]]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加