Skip to content

Instantly share code, notes, and snippets.

@antimatter15
Created February 16, 2012 03:22
Show Gist options
  • Save antimatter15/1841460 to your computer and use it in GitHub Desktop.
Save antimatter15/1841460 to your computer and use it in GitHub Desktop.
Pseudocode to Graphviz Converter
Place phone call.
Home?
Leave message
Wait for callback
"Would you like to share a meal"
"Would you like to share a meal"
What is the response (A) ?
"Do you enjoy a hot beverage"
What is the response (B) ?
n = 0
"recreational activity? tell me one of your interests"
Do I share that interest?
n = n + 1
n > 6?
"recreational activity? tell me one of your interests"
Choose least objectionable interest
Partake in interest
"Why don't we do that together"
Partake in interest
Begin friendship.
Is it tea?
Is it coffee?
Is it cocoa?
Have whatever that person said
Begin friendship.
Have cocoa
Begin friendship.
Have coffee
Begin friendship.
Have tea
Begin friendship.
Dine together
Begin friendship.
import sys
indent = 0
last = []
print "digraph G {"
for line in sys.stdin:
count = 0
while line.startswith("\t"):
count += 1
line = line[1:]
if count > indent:
indent += 1
last.append(last[-1])
elif count < indent:
indent -= 1
last = last[:-1]
line = line.strip().replace('"', '\\"')
if line.endswith("?"):
print '"'+line+'"', "[shape=diamond]"
elif line.endswith("."):
print '"'+line+'"', "[shape=ellipse]"
else:
print '"'+line+'"', "[shape=box]"
if len(last) > 0:
label = ""
if last[-1].endswith("?"):
if len(last) > 1 and last[-1] == last[-2]:
label = '[label="No"]'
else:
label = '[label="Yes"]'
print '"'+last[-1]+'"', '->', '"'+line+'"', label
last = last[:-1]
last.append(line)
print "}"

Everything's processed pretty much sequentially. If you treat every item as a list, it draws an arrow from one thing to another. Awesome.

But what if you want something cooler? Say, conditionals. Yeah. those are cool. So if you have that, you need my magical notation which involves lots of indentation.

Home?
	Oh noes, the condition's answer was No
	This has an arrow pointing from the thing above
Yaay, the answer was yes
Stuff that follows...

Ellipse'd elements end with periods.

Also, this is how you'd run it:

cat algorithm.pseudo | python parser.py | dot -Tsvg > blah.svg

@leopck
Copy link

leopck commented May 19, 2019

Hey, great code. Thanks for sharing. I converted this code into Javascript and based on WebGraphiViz. So it's now able to run independently on a web browser. Go ahead and try it.

https://github.com/leopck/codeflow
https://fridayswithfaraday.com/codeflow/

Your code falls under Sample 6.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment