[Tutor] stopping a loop [cross product instead of nested loops]

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 6 May 2001 02:10:20 -0700 (PDT)


On Sat, 5 May 2001, Sheila King wrote:

> On Sat, 05 May 2001 20:24:52 -0500, "Julieta Rangel" <julieta_rangel@hotmail.com>
> wrote about RE: [Tutor] stopping a loop:
> 
> :Are you implying a tripple nested loop?  meaning
> :for x in set:
> :    for y in set:
> :        for z in set:
> :           if ['x',('y','z')] == [('x','y'),'z']:
> :              return associativity holds
> :
> :Is this what you mean?  If I give the computer those commands, will it look 
> :for the definition on my dictionary?  You see, I'm not sure how I'm supposed 
> :to tell the computer to look in the dictionary for these values and compare 
> :them.  Any more hints, ideas, suggestions, comments, questions?
> :
> :Julieta
> 
> I'm not sure if Tim was implying a triply-nested loop, or not. It sounded kind of
> like it to me, too. However, a double-nested loop will do fine.
> 
> The key is, you need to use your dictionary to look up the values of the operations.
> That is the key. That is why you built the dictionary in the first place.


You might find the following definition useful: it's a way of producing
the "cross" product of two lists:

###
def cross(set1, set2):
    resulting_set = []
    for s1 in set1:
        for s2 in set2:
            resulting_set.append( (s1, s2) )
    return resulting_set
###


One reason why the cross product is so useful is because, given any two
lists, it can give back to us all possible pairs of those two lists, all
in a nice list:

###
>>> cross([1, 2, 3, 4], [1, 2, 3, 4])
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1),
(3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
###

Or, more evocatively:

###
>>> numbers = ['1', '2']
>>> cross(numbers, cross(numbers, numbers))
[('1', ('1', '1')), ('1', ('1', '2')), ('1', ('2', '1')),
 ('1', ('2', '2')), ('2', ('1', '1')), ('2', ('1', '2')),
 ('2', ('2', '1')), ('2', ('2', '2'))] 
###

By using the function above, you might not even need any nested loops in
your own code.


Hope this helps!