
Untitled
By: a guest on
Apr 30th, 2012 | syntax:
None | size: 0.92 KB | hits: 12 | expires: Never
Algorithm to generate (not quite) spanning set in Python with no set longer than 5
[1] [2] [3] [4] [5] [6] [7]
[1] [2] [3] [4] [5] [6, 7]
[1] [2] [3] [4] [5, 6, 7]
...
...
[1, 2, 3, 4, 5] [6, 7]
[1, 2, 3, 4, 5, 6] [7]
or
[1, 2, 3, 4, 5, 6, 7]
def span(lst):
yield [lst]
for i in range(1, len(lst)):
for x in span(lst[i:]):
yield [lst[:i]] + x
def span(lst, most=float("inf")):
if not lst:
yield []
return
for i in range(1, min(len(lst), most) + 1):
for x in span(lst[i:], most):
yield [lst[:i]] + x
lst = [1,2,3,4,5,6,7]
n = 5
spannings = list(span(lst, n))
print 'n'.join(map(str, spannings))
# proof that it produces the correct result
assert sorted(spannings) == sorted(s for s in span_orig(lst) if max(map(len, s)) <= n)
# proof that it produces the same result as the old
# function if called without a second argument
assert sorted(span_orig(lst)) == sorted(span(lst))