[英]recursive sequentially powerset function in python
what I expect for [1,2,3] ->我对 [1,2,3] 的期望 ->
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]
but my function give this result, I can not fix it ->但是我的 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]
and in some situation I want to stop calculation and continue with others:在某些情况下,我想停止计算并继续其他人:
let say if 1 and 2 get come together, dont continue anymore假设1和2走到一起,不要再继续了
-> for [1,2,3] and (1,2) -> 对于 [1,2,3] 和 (1,2)
what I expect:我的期望:
[1]
[1, 3]
[2]
[2, 3]
[3]
iterative function is also good for me迭代 function 对我也有好处
Another way to think about the problem doesn't involve ranges, indexes or incrementing them, leading to many off-by-one errors .考虑问题的另一种方法不涉及范围、索引或递增它们,这会导致许多错误。 Instead we can reason about the problem inductively -相反,我们可以归纳地推理这个问题——
t
is empty, yield the empty set如果输入t
为空,则产生空集t
has at least one element. (感性) t
至少有一个元素。 For all p
in the recursive sub-problem powerset(t[1:])
, yield p
and yield p
with the first element, t[0]
prepended.对于递归子问题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)
By using yield
we move the desired effect outside of the powerset
function.通过使用yield
,我们将所需的效果移到了powerset
function之外。 This allows the caller to decide what happens with each produced set -这允许调用者决定每个生成的集合会发生什么 -
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)
powerset([1,2,3,4,5])幂集([1,2,3,4,5])
Output: 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]
it could be better but that's all I could do它可能会更好,但这就是我所能做的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.