AlexJJ
AlexJJ

Reputation: 93

Python :get possibilities of lists and change the number of loops

I'd like to be able to change the number of loops and store all possibilities in a (list of lists). Let me explain by an example:

You have the following list:

 initial_list=[1,2]

Then you have a parameter n, which is the number of loops

For example if n=2, I'd like my programm to return this list:

 final_list=[[x,x,1,2],[x,1,x,2],[x,1,2,x],[1,x,x,2],[1,x,2,x][1,2,x,x]]

So for n=3, the program would do the same with 3 'x', etc

Also, i'd like my initial_list could have different length, like [1,2,3] or [1,2,3,4], etc

I know how to do that if the parameter n is hardcoded ( by n loop) but is it possible to do that if n change?

Thanks and sorry for my bad explaination ^^

Upvotes: 1

Views: 80

Answers (3)

Kelly Bundy
Kelly Bundy

Reputation: 27588

You could let itertools.combinations give you indexes where to insert 'x':

for indexes in combinations(range(len(initial_list) + n), n):
    tmp = initial_list[:]
    for i in indexes:
        tmp.insert(i, 'x')
    print(tmp)

Output:

['x', 'x', 1, 2]
['x', 1, 'x', 2]
['x', 1, 2, 'x']
[1, 'x', 'x', 2]
[1, 'x', 2, 'x']
[1, 2, 'x', 'x']

Upvotes: 0

jimsu2012
jimsu2012

Reputation: 170

Use itertools.permutations:

import itertools

def permutations(initial_list, n, x):
    return list(itertools.permutations(initial_list + [x] * n))

Upvotes: 1

Nathan
Nathan

Reputation: 3648

You can do this with a recursive function:

def get_lists(lst, n, sol):
    if len(lst) == 0 and n == 0:
        return [sol]
    solutions = []
    if len(lst) > 0:
        solutions += get_lists(lst[1:], n, sol + [lst[0]])
    if n > 0:
        solutions += get_lists(lst, n - 1, sol + ['x'])
    return solutions

n = 2
initial_list = [1, 2]
print(get_lists(initial_list, n, []))
>>> [[1, 2, 'x', 'x'], [1, 'x', 2, 'x'], [1, 'x', 'x', 2], ['x', 1, 2, 'x'], ['x', 1, 'x', 2], ['x', 'x', 1, 2]]

The way it works:

  1. You input your original list and number of x's n, as well as an empty list as the original 'solution'
  2. It checks if either the length of your list, or n is larger than 0
  3. If not, it returns the current solution
  4. Otherwise, it adds onto the solution, and goes back to step 2

This is slightly more complicated than the permutations idea, however, when your list or n becomes large, this will be much faster because you won't have to worry about removing doubles.

Upvotes: 1

Related Questions