J
jonny.longrigg
Hi
I'm having some trouble with a function I've written in Python:
def myFunction(l1,l2,result=[]):
index=0
for i in l1:
result.append([])
if type(i)==list:
myFunction(i,l2,result[index])
else:
for j in l2:
result[index].append(i*j)
index+=1
return result
l1 and l2 are lists and the function multiplies every element of l1
with every element of l2. l1 is (possibly) multi-dimensional, and the
recursive bit is in there to cope with that. For example, if
l1=[[1,2],[3,4]] and l2=[5,6] the result is
[[[5,6],[10,12]],[[15,18],[20,40]]].
The problem is that it works if I run it once, but then on repeated
runs the value for 'result' doesn't seem to set itself to my default of
[], but instead uses the state it was in last time the function was
run.
I've had a problem like this in the past and ended up rewriting the
function as a class and using something like self.result, but I don't
really like this solution as the code becomes considerabley more
difficult to read (and I suspect less efficient). Also, I suppose I
could feed in an empty array every time but that doesn't provide a very
intuitive interface to the function.
Does anyone know what is going on here? Is there an easy solution?
Thanks for your help!
I'm having some trouble with a function I've written in Python:
def myFunction(l1,l2,result=[]):
index=0
for i in l1:
result.append([])
if type(i)==list:
myFunction(i,l2,result[index])
else:
for j in l2:
result[index].append(i*j)
index+=1
return result
l1 and l2 are lists and the function multiplies every element of l1
with every element of l2. l1 is (possibly) multi-dimensional, and the
recursive bit is in there to cope with that. For example, if
l1=[[1,2],[3,4]] and l2=[5,6] the result is
[[[5,6],[10,12]],[[15,18],[20,40]]].
The problem is that it works if I run it once, but then on repeated
runs the value for 'result' doesn't seem to set itself to my default of
[], but instead uses the state it was in last time the function was
run.
I've had a problem like this in the past and ended up rewriting the
function as a class and using something like self.result, but I don't
really like this solution as the code becomes considerabley more
difficult to read (and I suspect less efficient). Also, I suppose I
could feed in an empty array every time but that doesn't provide a very
intuitive interface to the function.
Does anyone know what is going on here? Is there an easy solution?
Thanks for your help!