[Tutor] [cross product instead of nested loops]
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Sun, 6 May 2001 19:55:06 -0700 (PDT)
On Sun, 6 May 2001, Julieta Rangel wrote:
> I've been playing with the cross product definition you gave me. It makes a
> lot of sense, and I'm sure it will make it a lot easier for me to prove
> associativity; however, I'm doing something wrong because when I run it, I
> don't get the result I thought I would. Would you take a look and tell me
> what I'm doing wrong?
>
>
> def cross(set1,set2):
> resulting_set = []
> for s1 in set1:
> for s2 in set2:
> resulting_set.append( (s1, s2) )
> return resulting_set ## <-- bug!
There's a bug here: we want to return the resulting_set only after we
finish going through both for loops. That is:
###
def cross(set1,set2):
resulting_set = []
for s1 in set1:
for s2 in set2:
resulting_set.append( (s1, s2) )
return resulting_set
###
The difference is in indentation, but the idea is that the request about
returning a result should be outside of the looping. After fixing this,
the program should work ok.