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))]
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.