Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    Strangest line of python you have ever seen

    An example of a NFA state diagram.

    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

    Published on November 18th, 2011 in Uncategorized

    Did you enjoy this article?

    Continue reading about Strangest line of python you have ever seen

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️