[Tutor] Unique values in an array.

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 28 May 2001 15:02:52 +0200


On  0, "Rod Krause (School)" <rod.krause@dubbocs.com.au> wrote:
> I am trying to generate 20 unique questions for testing numeracy skills in
> high school students. Assuming that I want to generate a simple question for
> adding two integers eg x+y what I am doing is radnomly generating x and y
> and testing to see whether this combination has already been used.  Normally
> I have placed the generated x into an one array and y into another.  When
> the next x is generated I test to see if it is already in the array.  If it
> is it is rejected and a new integer is generated.

But that means that no x can be used twice - you said you wanted to check
for unused *combinations* - it could ask for both 14+7 and 14+21, right?

> I am trying to find out how to read numbers into an array using Python and
> then testing a new integer to see if it has been used.  The aim is to
> generate 20 unique questions when the program is run.
> 
> I am not sure of array usage in Python - or maybe an alternative.  Can
> anybody give me a little direction.

A dictionary is better, I think. You can add keys like (3,4) to the
dictionary (we just use a dummy value, it's the keys that matter). So that
if we have the sums 3+4, 5+7 and 13+4, the dictionary would look like

{ (3,4): None,
  (5,7): None,
  (13,4): None
  }
  
Now if we randomly find (3,4) again and add it, the dictionary doesn't
change since it's already in there. We can just add random combinations
until the dictionary is of the desired size.

This makes a dictionary with 20 different combinations, with numbers between
1 and 50, and then prints them as sums:

from random import randrange

dict = {}
while len(dict) < 20:
    x = randrange(0,50)+1
    y = randrange(0,50)+1
    dict((x,y)) = None

for combination in dict.keys():       # We can loop over the dictionary keys
    x, y = combination
    print x, "+", y, "="

You could also have done it with lists in which you store the tuples. Then
you have to manually check if the tuple is in the list already, though:

l = []
while len(l) < 20:
   x = randrange(0,50)+1
   y = randrange(0,50)+1
   if (x,y) not in l:
      l.append((x,y))

for combination in l:
   x, y = combination
   print x, "+", y, "="
   
For large lists, the dictionary will be alot faster, but for 20 combinations
it's a matter of taste.

-- 
Remco Gerlich