0

I am trying to define a function that will take in a list of lengths from a shape like this:

enter image description here

And return the coordinates of each point.

Here is what have so far:

def cord(lst):
    lst2 = [[0,0]]
    d = 'up'
    c = [0,0]
    for n in lst:
        if d == 'up': # if the direction is up, we add the value to the y cor
            c[1] += n
            lst2.append(c)
            d = 'right' # After up, we go right

        else: # if the direction is right, we add the value to the x cor
            c[0] += n
            lst2.append(c)
            d = 'up' # After right, we go up

    print(lst2)

cord([10,10,10])

Output:

[[0, 0], [10, 20], [10, 20], [10, 20]]

Desired output:

[[0, 0], [0, 10], [10, 10], [10, 20]]

Can you tell me what's wrong?

Red
  • 26,798
  • 7
  • 36
  • 58
  • That's what it's supposed to do, we keep adding a value to the coordinate to get the next coordinate. – Red May 31 '20 at 20:14
  • Does this answer your question? [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – MisterMiyagi May 31 '20 at 20:16
  • 1
    Note that you may want to use tuples instead of lists. Since a tuple is immutable, you cannot accidentally modify another reference to it. – MisterMiyagi May 31 '20 at 20:16
  • @MisterMiyagi That's what it's supposed to do, we keep adding a value to the x coordinate or y coordinate to get the next coordinate. – Red May 31 '20 at 20:17
  • Sorry, I don't understand how that relates to what I wrote. – MisterMiyagi May 31 '20 at 20:20
  • I mean only part of the coor can be converted tuples, others need to be overwritten. – Red May 31 '20 at 20:23
  • @MisterMiyagi Tuples wouldn't work because you can't do something like `c[0] += n` with tuple. – Asocia May 31 '20 at 20:25
  • 1
    @Asocia I'm not claiming a tuple can be substituted verbatim. The code doesn't work correctly in the first place, though. Adapting the code to tuples isn't more of a change than fixing the list usage. – MisterMiyagi May 31 '20 at 20:28

1 Answers1

4

Since lists are mutable and your variable c is a list, you need to append a copy of c so that it will not affect others when you change it. Do:

lst2.append(c.copy())
Asocia
  • 5,935
  • 2
  • 21
  • 46
  • yes good point and this is what you have in deepcopy for instance. The fact is that you reference to the same variable and to break this you need to create another reference – Laurent B. May 31 '20 at 20:28