Skip to content
Swizec Teller - a geek with a hatswizec.com

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

Enhanced by Zemanta

Did you enjoy this article?

Published on November 18th, 2011 in Uncategorized

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

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

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

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 ❤️