Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating random pairs from lists

I am trying to create a program that will print pairs of the elements in a list. I need to create a dictionary (that is empty at first) where I can store values, Loop through the list to make a pair and make sure there are no duplicates.

When I loop in the list, I need to get a random number and I can use it to remove an element. Remove the randomly selected element from the list using pop method, store the element to a variable, say element1. Repeat it to create element2.

Map the element1 to element2 by inserting the element1 as key to the pairs dictionary, and setting its value to element2, that is, if we call pairs[element1] later it should give us the value of element2.

Print the result using dictionary’s items() and keys() methods.

The catch is, the only function we are allowed is the random.randrange()from the random module :(

Example is this:

list = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]

Sample run of the program, this creates 3 pairs because there are 6 elements in the list.

Pair 1: Mother and Aunt
Pair 2: Uncle and Sister 
Pair 3: Brother and Father

Here is my program for now:

family = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]

for x in family:


pairs = {}

How can I improve/add to this code?

like image 258
Tony Garangean Avatar asked Feb 26 '15 17:02

Tony Garangean


2 Answers

Using random.randrange to select (and remove) a random element from a list is easy:

def pop_random(lst):
    idx = random.randrange(0, len(lst))
    return lst.pop(idx)

Now, assuming that the list has an even number of elements, we can build pairs very easily:

pairs = []
while lst:
    rand1 = pop_random(lst)
    rand2 = pop_random(lst)
    pair = rand1, rand2
    pairs.append(pair)

There are 2 steps missing that I'll leave as an exercise for you:

  1. Make sure the list is unique before you start
  2. Make sure the unique list has an even number of elements (and figure out what to do if it doesn't ...)
like image 172
mgilson Avatar answered Sep 21 '22 16:09

mgilson


import random

family = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]
pairs = {}

for p in range(len(family) // 2):
    pairs[p+1] = ( family.pop(random.randrange(len(family))),
        family.pop(random.randrange(len(family))) )

print(pairs)
like image 26
Lee Daniel Crocker Avatar answered Sep 20 '22 16:09

Lee Daniel Crocker