user3180110
user3180110

Reputation: 53

Creating a list of all possible nested sequences from another list

 List1=[0, 1, 2, 3, 4, 5]

I'd like to produce the following list2 containing four-element nested sequences from list1.

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

The eventual problem will use list1 with more elements and list2 with more than four-element nested sequences. However, I believe the logic is the same and hope the example is clear.

I'm basically looking for all “x-element” progressive nested sequences possible from a given list1.

I've written a loop to produce list2 with three-element nested sequences. Unfortunately, my solution is ugly and the more elements in my nested sequences, the uglier it gets. My guess/hope is this is a known math problem with a simple Python solution. My research leads me to believe it's a recursion problem, but I'm having a difficult time translating it into code.

Upvotes: 3

Views: 82

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 114025

Look up itertools.combinations

Basically, what you are looking for is:

import itertools
itertools.combinations([0, 1, 2, 3, 4, 5], 4)

Upvotes: 8

Related Questions