Home > Software design >  Faster and more pythonic way to reproduce unique set of unordered random numbers inside nested list
Faster and more pythonic way to reproduce unique set of unordered random numbers inside nested list

Time:07-04

I wanted to create a domino game. I'm in the beginning of my journey to become a python dev. I have made enough progress but I'm wondering if i could refactor my unique set generator function more elegant - pythonic and shorter.
This is my function and i think it is working as it should be. All the other functions in the program are depended on this.

The main job of the function is creating a list of unique set of two random numbers (0-6(including)) range and all of those lists are inside a list. For ex. [1,2] and [2,1] are the same and should appear only once in the final array.

from random import randrange

length = 28


def unique_set_generator(set_size):
    unique_set = set()
    main_set = []
    while len(unique_set) != set_size:
        x, y = randrange(7), randrange(7)
        if (x, y) not in unique_set and (y, x) not in unique_set:
            unique_set.add((x, y))
    
    set_to_list = list(unique_set)

    for i in range(set_size):
        main_set.append(list(set_to_list[i]))

    return main_set


print(unique_set_generator(length))

Outcome:
[[4, 3], [5, 4], [2, 2], [1, 0], [1, 3], [6, 5], [4, 2], [3, 3], [5, 0], [3, 6], [5, 3], [1, 2], [0, 4], [1, 5], [6, 1], [6, 4], [3, 2], [5, 2], [4, 4], [5, 5], [0, 0], [1, 1], [0, 3], [2, 0], [1, 4], [2, 6], [6, 0], [6, 6]]

CodePudding user response:

Use the tools Python provides:

import random

dominos = [(i,j) for i in range(7) for j in range(i,7)]
print(dominos)
random.shuffle(dominos)
print(dominos)
  • Related