Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python random list

I'm new to Python, and have some problems with creating random lists.

I'm using random.sample(range(x, x), y).

I want to get 4 lists with unique numbers, from 1-4, so I have been using this

a = random.sample(range(1, 5), 4)
b = random.sample(range(1, 5), 4)
c = random.sample(range(1, 5), 4)
d = random.sample(range(1, 5), 4)

So I get for example

a = 1, 3, 2, 4
b = 1, 4, 3, 2
c = 2, 3, 1, 4
d = 4, 2, 3, 1

How can I make it that the column are also unique?

like image 840
PythonUserNew Avatar asked Nov 27 '15 15:11

PythonUserNew


3 Answers

Absent a clear mathematical theory, I distrust anything other than a somewhat hit-and-miss approach. In particular, backtracking approaches can introduce a subtle bias:

from random import shuffle

def isLatin(square):
    #assumes that square is an nxn list
    #where each row is a permutation of 1..n
    n = len(square[0])
    return all(len(set(col)) == n for col in zip(*square))

def randSquare(n):
    row = [i for i in range(1,1+n)]
    square = []
    for i in range(n):
        shuffle(row)
        square.append(row[:])
    return square

def randLatin(n):
    #uses a hit and miss approach
    while True:
        square = randSquare(n)
        if isLatin(square): return square

Typical output:

>>> s = randLatin(4)
>>> for r in s: print(r)

[4, 1, 3, 2]
[2, 3, 4, 1]
[1, 4, 2, 3]
[3, 2, 1, 4]
like image 70
John Coleman Avatar answered Sep 22 '22 01:09

John Coleman


Totally random then:

def gen_matrix():
    first_row = random.sample(range(1, 5), 4)
    tmp = first_row + first_row
    rows = []
    for i in range(4):
        rows.append(tmp[i:i+4])
    return random.sample(rows, 4)
like image 36
Maciek Avatar answered Sep 22 '22 01:09

Maciek


Create a list of all the elements, and as will filling the line, remove the used element.

import random

def fill_line(length):
    my_list = list(range(length))

    to_return = []

    for i in range(length):
        x = random.choice(my_list)

        to_return.append(x)
        my_list.remove(x)

    return to_return

x = [fill_line(4)
     for i in range(4)]

print(x)
like image 26
macabeus Avatar answered Sep 18 '22 01:09

macabeus