Skip to content
Advertisement

Find neighbors coordinate (python)

I am creating code that calculates neighbor coordinates to passed coordinate.

I have list of lists with “directions” I want move to, first number is X-value, second number is Y-value.

JavaScript

Then I have a function to calculate new coordinates and store them in a list “results”

JavaScript

Example: if I pass coordinate [2, 3]

Then correct output should be list with coordinates: [2, 4] [2, 2], [3, 3], [1, 3]

Well but what happens to me is that its adding +1, but not substracting -1 so my output look like this: [2, 4], [2, 3], [3, 3], [2, 3].

Advertisement

Answer

Okay, so that code does not do what you intend it to do. Lists are mutable which means that

JavaScript

an option would be to use copy

JavaScript

but even with that, there are things to change here cause your code is hard to reason about, it would be better to do that

JavaScript

it’s shorter, more beautiful and way easier to reason about

EDIT: But it can be even better actually, it can be a clear one liner

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement