簡體   English   中英

python中的遞歸順序powerset function

[英]recursive sequentially powerset function in python

我對 [1,2,3] 的期望 ->

[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

但是我的 function 給出了這個結果,我無法修復它->

def foo(L,first,last,Output):
    if first>=last:
        return
    for i in range(first ,last):
        print(Output+[L[i]])
        foo(L,first+1,last,Output+[L[i]])
        


foo([1,2,3],0,3,[])


[1]
[1, 2]
[1, 2, 3]
[1, 3]
[1, 3, 3]
[2]
[2, 2]
[2, 2, 3]
[2, 3]
[2, 3, 3]
[3]
[3, 2]
[3, 2, 3]
[3, 3]
[3, 3, 3]

在某些情況下,我想停止計算並繼續其他人:

假設1和2走到一起,不要再繼續了

-> 對於 [1,2,3] 和 (1,2)

我的期望:

[1]
[1, 3]
[2]
[2, 3]
[3]

迭代 function 對我也有好處

考慮問題的另一種方法不涉及范圍、索引或遞增它們,這會導致許多錯誤 相反,我們可以歸納地推理這個問題——

  1. 如果輸入t為空,則產生空集
  2. (感性) t至少有一個元素。 對於遞歸子問題powerset(t[1:])中的所有p ,yield p和 yield p加上第一個元素t[0]
def powerset(t):
  if not t:
    yield ()                       # 1. empty t
  else:
    for p in powerset(t[1:]):      # 2. at least one element
      yield p
      yield (t[0], *p)

通過使用yield ,我們將所需的效果移到了powerset function之外 這允許調用者決定每個生成的集合會發生什么 -

for p in powerset("abc"):
  print(p)                   # <- desired effect
()
('a',)
('b',)
('a', 'b')
('c',)
('a', 'c')
('b', 'c')
('a', 'b', 'c')
for p in powerset("abc"):
  print("".join(p))     # <- different effect
a
b
ba
c
ca
cb
cba
def helper(L,first,last,Output,isBack):
    if first>=last-1:
        return
    
    for i in range(first ,last):
        if L[i] in Output:
            continue
        print(Output+[L[i]])
        
        if isBack:
            helper(L,first+i,last,Output+[L[i]],False)
            
        else:
            helper(L,first+1,last,Output+[L[i]],False)
            
        isBack=True

def powerset(L):
    helper(L,0,len(L),[],True)

冪集([1,2,3,4,5])

Output:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
[1, 2, 4]
[1, 2, 5]
[1, 3]
[1, 3, 5]
[1, 4]
[1, 5]
[2]
[2, 3]
[2, 3, 4]
[2, 3, 4, 5]
[2, 3, 5]
[2, 4]
[2, 5]
[3]
[3, 4]
[3, 4, 5]
[3, 5]
[4]
[4, 5]
[5]

它可能會更好,但這就是我所能做的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM