How to create permutations of a list without moving zeros. in python

using the itertools tool, I have every possible permutation of a given list of numbers, but if the list looks like this:

 List=[0,0,0,0,3,6,0,0,5,0,0] 

itertools does not “know” that iterating over zeros is wasted work, for example, the following iterations will be displayed in the results:

 List=[0,3,0,0,0,6,0,0,5,0,0] List=[0,3,0,0,0,6,0,0,5,0,0] 

they are the same, but itertools just takes the first zero (for example) and moves it to fourth place in the list and vice versa.

The question arises: how can I iterate over only some selected numbers and leave others alone, such as zero? It can be with or without itertools .

+8
python list permutation
source share
3 answers

Voilá - now it works - after receiving permutations for “meat” I get all possible combinations for positions “0” and yield one permutation for each possible set of “0 positions” for each permutation of non-0s:

 from itertools import permutations, combinations def permut_with_pivot(sequence, pivot=0): pivot_indexes = set() seq_len = 0 def yield_non_pivots(): nonlocal seq_len for i, item in enumerate(sequence): if item != pivot: yield item else: pivot_indexes.add(i) seq_len = i + 1 def fill_pivots(permutation): for pivot_positions in combinations(range(seq_len), len(pivot_indexes)): sequence = iter(permutation) yield tuple ((pivot if i in pivot_positions else next(sequence)) for i in range(seq_len)) for permutation in permutations(yield_non_pivots()): for filled_permutation in fill_pivots(permutation): yield filled_permutation 

(I used the "nonlocal" keyword of Python 3 - if you are still on Python 2.7, you will need to take a different approach, for example make a seq_len list with one element, which you can then replace with an internal function)

My second attempt (the worker is actually the third)

This is a naive approach that simply stores the cache of already "seen" permutations - it saves the work that is performed for each permutation, but does not work to generate all possible permutations:

 from itertools import permutations def non_repeating_permutations(seq): seen = set() for permutation in permutations(seq): hperm = hash(permutation) if hperm in seen: continue seen.add(hperm) yield permutation 
+3
source share

Add each result to the list. You will now have every possible combination, and then do the following:

 list(set(your_big_list)) 

Set restricts the list to only unique permutations. I'm not completely sure if this is the problem you are trying to solve, or you are worried about performance. Regardless, I just made an account, so I decided to try something

0
source share

Your questions are unclear, but if you are trying to list permutations without having 0 in your output, you can do it like this:

 from itertools import permutations def perms( listy ): return permutations( [i for i in listy if i!=0]) 
0
source share

All Articles