Iterating over sections in Python

I was wondering what is the best way (in Python) to iterate over sections from a list of a given size.

Say, for example, we have a list [1,2,3,4,5]and we want sections k=3. A bad way to do this is to write:

lst = [1,2,3,4,5]
for i in range(1,len(lst)):
    for j in range(i+1, len(lst)):
        print lst[:i], lst[i:j], lst[j:]

This gives

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

But if I later wanted to iterate over sections k=4, then I would have to add a level for nesting loops, which cannot be done at runtime. Ideally, I would like to write something like:

for part in partitions([1,2,3,4,5], k):
    print part

Does anyone know a better way to do this?

+4
source share
3 answers

I would use the same idea as yours without pairwise:

from itertools import combinations

def partitions(items, k):

    def split(indices):
        i=0
        for j in indices:
            yield items[i:j]
            i = j
        yield items[i:]

    for indices in combinations(range(1, len(items)), k-1):
        yield list(split(indices))
+1
source

, , :

from itertools import tee, izip, combinations

def partitions(items, k):
    N = len(items)

    def pairwise(iterable):  # Taken from itertools recipies
        a, b = tee(iterable)
        next(b, None)
        return izip(a, b)

    def applyPart(part, items):
        lists = []
        for l,h in pairwise([0] + part + [N]):
            lists.append(items[l:h])
        return lists

    for part in combinations(range(1, N), k - 1):
        yield applyPart(list(part), items)
+2

This may be somewhat inefficient for large lists, but it works:

from itertools import product, islice

def partitions(seq, k):
    for c in product(xrange(1, len(seq)+1), repeat=k):
        if sum(c) == len(seq):
            it = iter(seq)
            yield [list(islice(it, x)) for x in c]

for part in partitions([1,2,3,4,5], 3):
    print part

Conclusion:

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

For large lists, you need to find all subsets of ksize range(1, len(sequence)+1)that add up to the length of the sequence and then cut the sequence based on them.

Associated: http://www.algorithmist.com/index.php/Coin_Change

0
source

Source: https://habr.com/ru/post/1540126/


All Articles