Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Strangest line of python you have ever seen

  Swizec Teller        2011-11-19 02:05:03       2,056        0    

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.

state = [st for s in state for st in states[(s,letter)]]

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

from optparse import OptionParser
from collections import defaultdict
 
def run(beseda):
       a, states = open("machine.txt") ,defaultdict(list)
       state, final= a.readline().split()[1:],a.readline().split()[1:]
       [states[(i.split()[0], i.split()[1])].append(i.split()[3]) for i in a]
       for letter in word:
               state = [st for s in state for st in states[(s,letter)]]
       return any(i in state for i in final)
 
print [(b,"YES") if run(b) else (b,"NO") for b in OptionParser().parse_args()[1]]

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

object NKA extends App {
    import scala.collection.mutable._
    val gates = new HashMap[(String,Char), ListBuffer[String]]
    val lines = io.Source.fromFile("avtomat.txt").getLines.toSeq
    val (init,finals) = (lines(0).split(" ")(1),lines(1).split(" ").tail)
    lines.tail.tail.map(_.split(" ")).foreach 
        {s => gates.getOrElseUpdate((s(0),s(1)(0)), ListBuffer()) += s(3)}
 
    def crawl(state:String, input:String):Boolean = 
        (input!="" && (false /: gates.getOrElse((state,input(0)), return false))
            {_ || crawl(_, input.tail)}) || (input=="" & finals.contains(state))
 
    args.foreach(in => println(in + (if(crawl(init,in)) ": YES" else ": NO")))

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:

  1. Explain how that line of python works
  2. 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

PYTHON  STRANGE  RESEARCH  WORK RATIONALE 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.