Search code examples
pythonrandomsamplemutual-exclusion

Mutually exclusive random sampling from a list


input = ['beleriand','mordor','hithlum','eol','morgoth','melian','thingol']

I'm having trouble creating X number of lists of size Y without repeating any elements.

What I have been doing is using:

x = 3
y = 2

import random

output = random.sample(input, y)
# ['mordor', 'thingol']

but if I repeat this then I will have repeats.

I would like the output to be something like

[['mordor', 'thingol'], ['melian', 'hithlum'], ['beleriand', 'eol']]

since I chose x = 3 (3 lists) of size y = 2 (2 elements per list).

def random_generator(x,y):
    ....

Solution

  • rather than randomly taking two things from your list, just randomize your list and iterate through it to create your new array of the dimensions you specify!

    import random
    my_input = ['beleriand','mordor','hithlum','eol','morgoth','melian','thingol']
    def random_generator(array,x,y):
        random.shuffle(array)
        result = []
        count = 0
        while count < x:
            section = []
            y1 = y * count
            y2 = y * (count + 1)
            for i in range (y1,y2):
                section.append(array[i])
            result.append(section)
            count += 1
        return result
    print random_generator(my_input,3,2)