Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all possible lists by replacing elements with 0

I would like to create from a list all the different list were 0,1,2,3...all element are replaced by an other For example, if the replacement item is 0:

L=[1,2,3]
->[1,2,3],[0,2,3],[1,0,3],[1,2,0],[0,0,3],[0,2,0],[1,0,0],[0,0,0]

So far, I've tried I managed to do what I whant using Itertools but only in the case where 1 value is replaced by 0 Does anyone know how to do this ?

like image 585
WouaToum Avatar asked Dec 23 '22 07:12

WouaToum


1 Answers

Everyone's trying too hard here. We want each value to be either the original value or 0 -- we want pairs like (1,0), (2,0), and (3,0):

>>> from itertools import product, repeat
>>> L = [1, 2, 3]
>>> zip(L, repeat(0))
<zip object at 0x7f931ad1bf08>
>>> list(zip(L, repeat(0)))
[(1, 0), (2, 0), (3, 0)]

and then we can just pass that into product:

>>> list(product(*zip(L, repeat(0))))
[(1, 2, 3), (1, 2, 0), (1, 0, 3), (1, 0, 0), (0, 2, 3), (0, 2, 0), (0, 0, 3), (0, 0, 0)]
like image 102
DSM Avatar answered Jan 13 '23 12:01

DSM