Welcome, guest | Sign In | My Account | Store | Cart

Using simple recursive logic.

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def partition(it):
    for i in range(len(it)):
        if i == len(it) - 1:
            yield [it[0:i+1]]
        else:                     
            for p in partition(it[i+1:]):
                yield [it[0:i+1]] + p


print list(partition(range(4)))

[[0], [1], [2], [3]]
[[0], [1], [2, 3]]
[[0], [1, 2], [3]]
[[0], [1, 2, 3]]
[[0, 1], [2], [3]]
[[0, 1], [2, 3]]
[[0, 1, 2], [3]]
[[0, 1, 2, 3]]
Created by Anoop.K on Tue, 3 May 2011 (MIT)
Python recipes (4591)
Anoop.K's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks