0

I just wanting to ask you about an excercise in school based on construction of a maze in python. We start with a known (x,y) point and the n*n graph. In each recursion we should make a neighbouring_list for every couple (x,y) which will contain the nearest elements of the point. So far I have written this code which shows correct results but I cannot save and manipulate exclusive the new x and y which are chosen from the neighbouring list. They perform in a way like (8,8) and i can't manage to write x = 8 and y = 8. Have you got any idea? Thank you in advance!

if(x and y == 0):
    neighbouring_list = [((x + 1), y), (x, (y + 1))]
elif (x == (n - 1) and y == 0):
    neighbouring_list = [((x - 1), y), (x, (y + 1))]
elif (y == 0):
    neighbouring_list = [((x + 1), y), ((x - 1), y), (x, (y + 1))]
elif (y == (n - 1) and x == 0):
    neighbouring_list = [(x, (y - 1)), ((x + 1), y)]
elif (x == 0):
    neighbouring_list = [(x, (y + 1)), (x, (y - 1)), ((x + 1), y)]
elif (x == (n - 1) and y == (n - 1)):
    neighbouring_list = [(x, (y - 1)), ((x - 1), y)]
elif (x == (n - 1)):
    neighbouring_list = [((x - 1), y), (x, (y + 1)), (x, (y - 1))]
elif (y == (n - 1)):
    neighbouring_list = [(x, (y - 1)), ((x - 1), y), ((x + 1), y)]
else:
    neighbouring_list = [((x - 1), y), ((x + 1), y), (x, (y + 1)), (x, (y -         1))]
nikiforosb
  • 23
  • 1
  • 1
  • 9
  • 3
    `if(x and y == 0):` should be `if(x == 0 and y == 0):` Also, not really clear what you are asking. What exactly is not working? Apart from that error, and thats its a bit longer than necessary, it seems to work okay. – tobias_k Mar 26 '15 at 09:27
  • I think that the two ways mentioned above are the same. What I really ask is for example if the neighbouring list is [(6,6), (7,6), (6,5)] and randomly the next visited point is the (6,6), to save the first 6 in the x variable and the second to y. x = 6 and y = 6 – nikiforosb Mar 26 '15 at 09:31
  • 1
    No, they are not the same. In fact, `if(x and y == 0):` is equivalent to `if(x != 0 and y == 0):` Do you mean you want to unpack an entry, like `x, y = neighboring_list[0]`? Also, I think `(6,6), (7,6), (6,5)` could not possibly be any neighbors list. – tobias_k Mar 26 '15 at 09:33
  • Yes, how to unpack this (x1, y1) to this x = x1 , y = y1 – nikiforosb Mar 26 '15 at 09:38
  • to unpack this (x1, y1) to this x = x1 , y = y1 do `x,y = x1,y1` – itzMEonTV Mar 26 '15 at 09:41

1 Answers1

2

Here's a much simpler version of your code:

nlist = []
if x < n:
    nlist.append((x+1,y))
if y < n:
    nlist.append((x,y+1))
if x > 0:
    nlist.append((x-1,y))
if y > 0:
    nlist.append((x,y-1))

That should be a lot easier to manage.

To unpack a tuple (xin, yin) into x, y for your code, you can simply do this:

x, y = (xin, yin)

or if the tuple is bound to a variable, say, coordinates:

x, y = coordinates

This is known as tuple unpacking.

Shashank
  • 13,713
  • 5
  • 37
  • 63