2

I'm trying to call a function recursively, and passing parts of the list to the function.

def op3(c,i):
    d = []
    for l in range(0,len(c),+1):
        d.append(c[l])
    a, b = [], []
    if len(d)>=3:
        for l in range(1,len(d)-1,+1):
            a.append(d[l])
        for l in range(2,len(d),+1):
            b.append(d[l])
        A,B = [],[]
        for j in range(0,len(a),+1):
            a[j][i] = a[j][i]+a[j][i+1]
            a[j].pop(i+1)
            insertf(a,final)
            A.append(a[j])
        op3(A,i+1)
        for k in range(0,len(b),+1):
            b[k][i+1] = b[k][i+1]+b[k][i+2]
            b[k].pop(i+2)
            insertf(b,final)
            B.append(b[k])
        op3(B,i+1)

but the values in the original list are changed in list 'b' to the new values of d after the first nested 'for' loop runs. i'm fairly new to python. i have read that this is just how lists work in python. is there a way around this?

2
  • 2
    Use an immutable data structure, like a tuple? Or newList=copy.deepcopy(otherList) to create a completely separate list? Commented Aug 31, 2013 at 11:37
  • 2
    You'd receive much more useful answers if, instead of asking about your solution, you asked about the real problem you are trying to solve with that function. See XY problem. Commented Aug 31, 2013 at 11:57

1 Answer 1

1

All the modified C-style for loops make my head hurt. Trying to parse...

def op3(c,i):
  d = c[:]
  if len(d)>=3:
    a=d[1:-1]
    b=d[2:]
    #A,B=[],[]
    for item in a:
      item[i] += item.pop(i+1)
      insertf(a,final)   # Totally unknown behaviour, does this modify a?
      #A.append(item)  # Seems pointless, A ends up a copy of a, and op3 
      #                # does not modify c (only its items)
    op3(a,i+1)
    for item in b:
      item[i+1] += item.pop(i+2)
      insertf(b,final)
    op3(b,i+1)

So from what the code does, it expects a list of lists, and it modifies the inner lists. It also calls itself recursively in a manner that seems to have no stop condition, but will break if the inner lists run out any((len(ci)<=i+2 for ci in c)).

On the whole, I'd say we can't provide a good answer because this code fragment just doesn't express what you want done. It seems likely the key point here is that lists are not two-dimensional; every list a[j] or b[k] is an independent object (though a[j] is b[j-1] since you extract them from the same list c), and has no knowledge of the manipulations you do on a,b,c,d,A,B.

Could you please describe what data structures you have and expect, and what sort of processing you're trying to do? It feels a bit like it would fit in about one expression of numpy.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.