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]]
\$\endgroup\$
  • 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\$ – butt Jan 10 at 1:28
  • 4
    \$\begingroup\$ @butt please don't use coments to write answers. Instead put answers into the answer box. Thanks! \$\endgroup\$ – Vogel612 Jan 10 at 9:57
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).

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.