The other day @HairyFotr and @zidarsk8 were doing some codegolfing with implementations of nondeterministic finite state machineand asked me to blog their results.
For those of us who often forget what all of this computer science mumbo jumbo means, here’s a quick explanation from wikipedia:
In the theory of computation, a nondeterministic finite state machine or nondeterministic finite automaton (NFA) is a finite state machine where for each pair of state and input symbol there may be several possible next states.
Essentially they were looking for the shortest implementation of an algorithm that can take a bunch of states, go through all of them on each step and then backtrack to find the solution.
@zidarsk8 doesn’t really know python all that well so his way to optimize things was basically “SHORTEN ALL THE CODES!†and as a result he came up with this line nobody understands.
At first it looks just like a double loop. But then you notice the right-most for is taking the list to iterate over from its own body, which is the iterator of the left-most for loop …
What?
Seriously, if you can explain how this works you win a lot of internets, eternal fame and I might just send you a box of cookies.
Here’s the whole implementation in case you were wondering
According to our best debugging efforts it works as advertised … even though we can’t actually understand why or how it’s even possible that python knows what to do.
For curiosity’s sake, here’s @HairyFotr’s Scala implementation
If you ask me, this looks like a bunch of gibberish and even HairyFotr says it isn’t the prettiest Scala code out there. But hey, this is codegolf, all that matters is minimizing those keystrokes!
To conclude, two challenges:
- Explain how that line of python works
- Come up with a shorter solution … I’m guessing golfscript is a good choice
PS: I was serious about those cookies
PPS: an example of what the automata decription looks like http://pastebin.com/QLW1BfFj
Source:http://swizec.com/blog/strangest-line-of-python-you-have-ever-seen/swizec/3012