Emmanuel
Emmanuel

Reputation: 149

How do you generate unique arrays from a list in python?

Suppose I have a simple list in python:

a = [0,1,2]

How do I generate unique arrays from this list so that I get:

arr_gen = [[0,1],
           [1,2],
           [0,2]]

I've tried using numpy.random.choice this way:

>>> np.random.choice(a, (3,2), replace = False)

But I get the following error below:

>>> ValueError: Cannot take a larger sample than population when 'replace=False'

Upvotes: 1

Views: 90

Answers (3)

Tharindu Gimras
Tharindu Gimras

Reputation: 43

Method 1

Just import combinations from itertools module in python. So by using this code you can get what you wanted.

>>> from itertools import combinations
>>> print(list(map(list,combinations([0, 1, 2], 2))))
[[0, 1], [0, 2], [1, 2]]

Method 2 (To get unique list)

In this question you also said that you need to generate unique arrays also, So lets assume that your array is [0,1,1].You just can use this one,

>>> from itertools import combinations
>>> print(list(map(list,{*map(tuple,combinations([0, 1, 2], 2))})))
[[0, 1], [1, 1]]

In sets removes duplicate items. So after that you have to convert set to list also.

Method 3 (Recursive method)

def myComb(lst):
    if len(lst) == 0:
        return []
    elif len(lst) == 1:
        return [lst]
    else:
        l = []
        for i in range(len(lst)):
            x = lst[i]
            xs = lst[:i] + lst[i+1:]
            for p in myComb(xs):
                l.append([x]+p)
        return l

ans=[]

for p in myComb([0,1,2]):
    p.pop()
    p.sort()
    if p not in ans:
        ans.append(p)

print(ans)

ans=[[0, 1], [0, 2], [1, 2]]

Upvotes: 1

Freeman
Freeman

Reputation: 12728

You can also solve this without using itertools, by using iterations and numpy

import numpy

def combinations(iterable, r): 
    char = tuple(iterable) 
    n = len(char) 
      
    if r > n: 
        return
      
    index = numpy.arange(r) 
    # retruns the first sequence  
    yield tuple(char[i] for i in index) 
      
    while True: 
          
        for i in reversed(range(r)): 
            if index[i] != i + n - r: 
                break
        else: 
            return
          
        index[i] += 1
          
        for j in range(i + 1, r): 
              
            index[j] = index[j-1] + 1
              
        yield tuple(char[i] for i in index) 
          
a = [0, 1, 2]
print([x for x in combinations(a, 2)]) 

Output :

[(0, 1), (0, 2), (1, 2)]

Upvotes: 1

Jacob Lee
Jacob Lee

Reputation: 4680

You could try using the built-in itertools module.

>>> import itertools
>>> a = [0, 1, 2]
>>> list(itertools.combinations(a, 2)
[(0, 1), (0, 2), (1, 2)]

Upvotes: 3

Related Questions