Skip to content

Instantly share code, notes, and snippets.

@sponnusa
Forked from antimatter15/algorithm.pseudo
Created September 22, 2020 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sponnusa/c9c49cc6f6dfdd03659940742f4f48db to your computer and use it in GitHub Desktop.
Save sponnusa/c9c49cc6f6dfdd03659940742f4f48db 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

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