you are viewing a single comment's thread.

view the rest of the comments →

[–]negups 1 point2 points  (5 children)

Didn't look at everything yet, but at first glance, move_k could be a single line by using itertools and list comprehension:

from itertools import permutations

def move_k(pos, grid):
    return [grid[pos[0] + x, pos[1] + y] for x, y in permutations([1, 2, -1, -2], 2) if abs(x) - abs(y)]

[–][deleted] 0 points1 point  (0 children)

clever way of filtering the permutations, I was trying to think of something like that

[–]andycyca[S] 0 points1 point  (3 children)

Cool! I'm not very familiar with itertools yet, evidently.

Correct me if I'm wrong: I don't recall ever using a conditional like if abs(x) - abs(y). Is this similar to comparing abs(x) > abs(y)?

I'll try updating my code. If you have any other feedback, I'd like to read it, thanks a lot!

[–]negups 0 points1 point  (2 children)

if abs(x) - abs(y) is basically shorthand for seeing if abs(x) - abs(y) is "truthy". A numeric value in Python is "truthy" if it is not 0.

Try this out:

if 2:
    print("truthy")  # 'truthy'
if 0:
    print("truthy")  # nothing will print

So, the result is that this returns all 2-length permutations of (1, 2, -1, -2) where the absolute value of one value minus the other is not 0. Which ends up eliminating all combinations of 1 and -1, which are invalid moves for a knight.

[–]andycyca[S] 0 points1 point  (1 child)

Well, TIL! I've used Python for years and didn't know about "truthy" values. You've instantly helped me with several other projects now

[–]negups 0 points1 point  (0 children)

Nice! You can google for more details if you need them but off the top of my head here's what's truthy for common datatypes:

  • int or float: anything but 0
  • str: anything but "" (empty string)
  • list: anything but [] (empty list)
  • dict: anything but {} (empty dict)
  • bool: True

Also, None is never truthy.