5
\$\begingroup\$

I did Advent of Code recently and enjoyed Day 15, which involves exploring a maze (my attempt in Kotlin). I've tried to recreate it partially in Python, minus the emulator:

https://repl.it/@MalcolmCrum/ReflectingFarNaturaldocs

It works but my code is largely 1:1 from Kotlin, and I'm not certain if I'm doing things in a Pythonic way. For example, I use this pattern regularly in Kotlin:

val direction = when (path.first()) {
 position + NORTH -> NORTH
 position + SOUTH -> SOUTH
 position + EAST -> EAST
 position + WEST -> WEST
 else -> error("Can't find first step from $position towards $destination in $path")
 }

The Python equivalent I found is this, which while nice and concise is maybe a little too "clever"? (ignore the 1 offset, I changed path logic slightly)

direction: Direction = {self.position + d: d for d in Direction}[path_to_destination[1]]
asked Jan 10, 2020 at 0:38
\$\endgroup\$
2
  • 3
    \$\begingroup\$ Using a dict to function as a when statement is a normal python practice, and people with mild python experience should know what you're doing if they see it. However you might consider revising your direction class. The index value of the tuple seems unnecessary, and perhaps could consider a method that returns a direction from two positions. Overloading the - operator might be reasonable, but it looks like a direction should only have a magnitude of length=1 which could not be guaranteed by subtracting two positions. \$\endgroup\$ Commented Jan 10, 2020 at 1:28
  • 4
    \$\begingroup\$ @butt please don't use coments to write answers. Instead put answers into the answer box. Thanks! \$\endgroup\$ Commented Jan 10, 2020 at 9:57

1 Answer 1

3
\$\begingroup\$

You have:

direction: Direction = {self.position + d: d for d in Direction}[path_to_destination[1]]

The dict is just mapping each key to key - self.position (I don't know your exact data models, but I'm going to assume that these are some kind of vector and that + and - behave in intuitive ways). Hence:

direction = path_to_destination[1] - self.position

and maybe:

assert abs(direction) == 1

if you want to require that direction is a unit vector (again, I'm assuming your vector representation is reasonable and implements __abs__ to return the magnitude).

answered Jan 10, 2020 at 8:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.