Random pairing with Python

I am adviser to a high school robotics team and wrote a small Python script to solve a pairing problem. We are starting our spring fund raising drive and I needed to randomly pair one student with one business. On my lunch break I hacked out the following script that solved the problem.

#import shuffle from random
from random import shuffle


with open("names", "r") as ins:
    names =[]
    for line in ins:
        names.append(line.rstrip('\n'))

# shuffle names
shuffle(names)

ins.close()

with open("businesses", "r") as ins:
    business =[]
    for line in ins:
        business.append(line.rstrip('\n'))

ins.close()

#shuffle businesses
shuffle(business)

c = []
c = [names[ix]+ " - " + business[ix] for ix in range (len(names))]

# print each pair on one line
for elem in c:
    print elem

The business file included a list of business with one on each line. the names file included student names with one on each line. The program simply imports each line, stripping the new line code, in to an array. Each array is randomized and then the program concatenates the two arrays before printing out the assignment pairs to the screen. I always enjoy demonstrating command line Linux to students.

Python script running on Fedora

Python script running on Fedora

This entry was posted in fedora-planet, FOSS, Programming, Ubuntu and tagged , , . Bookmark the permalink.

5 Responses to Random pairing with Python

  1. ak47 says:

    why do you close ins explicitly ?

  2. Warren T Mann says:

    # more pythonic?
    for elem in [“%s – %s” % (x,y) for x,y in zip(names, business)]:
    print elem

  3. Louis says:

    “I always enjoy demonstrating command line Linux to students”
    That’s Python, not really command line.
    Actually since this is text file handling, shell scripting is fully at home there and would give you :

    shuf business | paste names – | head -n $(wc -l names | cut -d\ -f1)

    or the more readable :

    students_count=$(wc -l names | cut -d\ -f1)
    shuf business > tmpBusiness
    paste names tmpBusiness | head -n $students_count

    Shell is a very powerful tool every computer user should have in his pocket.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s