[Numpy-discussion] lists of zeros and ones

josef.pktd@gmai... josef.pktd@gmai...
Fri Mar 19 10:40:28 CDT 2010


On Fri, Mar 19, 2010 at 11:24 AM,  <josef.pktd@gmail.com> wrote:
> On Fri, Mar 19, 2010 at 11:17 AM, Keith Goodman <kwgoodman@gmail.com> wrote:
>> On Fri, Mar 19, 2010 at 7:53 AM, gerardob <gberbeglia@gmail.com> wrote:
>>>
>>> Hello, i would like to produce lists of lists 1's and 0's.
>>>
>>> For example, to produce the list composed of:
>>>
>>> L = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
>>>
>>> I just need to do the following:
>>>
>>> n=4
>>> numpy.eye(n,dtype=int).tolist()
>>>
>>> I would like to know a simple way to generate a list containing all the
>>> lists having two 1's at each element.
>>>
>>> Example, n = 4
>>> L2 = [[1,1,0,0],[1,0,1,0],[1,0,0,1],[0,1,1,0],[0,1,0,1],[0,0,1,1]]
>>>
>>> Any ideas?
>>> Thanks.
>>
>> Here's the brute force way:
>>
>>>> for i in range(4):
>>   ....:     for j in range(i+1, 4):
>>   ....:         x = np.zeros(4)
>>   ....:         x[i] = 1
>>   ....:         x[j] = 1
>>   ....:         print x
>>   ....:
>>   ....:
>> [ 1.  1.  0.  0.]
>> [ 1.  0.  1.  0.]
>> [ 1.  0.  0.  1.]
>> [ 0.  1.  1.  0.]
>> [ 0.  1.  0.  1.]
>> [ 0.  0.  1.  1.]
>
> here are two numpy version, but they don't take any shortcuts
>
>
>>>> a= np.array(list(np.ndindex(*2*np.ones(4))))
>>>> a
> array([[0, 0, 0, 0],
>       [0, 0, 0, 1],
>       [0, 0, 1, 0],
>       [0, 0, 1, 1],
>       [0, 1, 0, 0],
>       [0, 1, 0, 1],
>       [0, 1, 1, 0],
>       [0, 1, 1, 1],
>       [1, 0, 0, 0],
>       [1, 0, 0, 1],
>       [1, 0, 1, 0],
>       [1, 0, 1, 1],
>       [1, 1, 0, 0],
>       [1, 1, 0, 1],
>       [1, 1, 1, 0],
>       [1, 1, 1, 1]])
>>>> a[a.sum(1)==2]
> array([[0, 0, 1, 1],
>       [0, 1, 0, 1],
>       [0, 1, 1, 0],
>       [1, 0, 0, 1],
>       [1, 0, 1, 0],
>       [1, 1, 0, 0]])
>
>
>>>> [list(r) for r in np.ndindex(*2*np.ones(4)) if sum(r)==2]
> [[0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 1, 0],
> [1, 1, 0, 0]]

just for fun
>>> ndim=5;n=3;nel=2;len([list(r) for r in np.ndindex(*n*np.ones(ndim)) if (np.array(r)!=0).sum()==nel])
40

Josef

>
> Josef
>
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion@scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>>
>


More information about the NumPy-Discussion mailing list