Skip to content

Instantly share code, notes, and snippets.

@mapio
Last active July 23, 2020 22:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mapio/70153b1750b3019d6764d5573135e7a0 to your computer and use it in GitHub Desktop.
Save mapio/70153b1750b3019d6764d5573135e7a0 to your computer and use it in GitHub Desktop.
Playing with my son Federico
from collections import deque
from subprocess import Popen, PIPE
from sys import argv
first, last = map(int, argv[1:3])
name = argv[3]
ops = [
lambda x: x + 1,
lambda x: x * 2
]
frontier = deque([first])
seen = set()
graph = 'graph G {\nnode [shape=point]'
while frontier:
v = frontier.popleft()
if v in seen: continue
for op in ops:
u = op(v)
if u > last: continue
graph += '\t{} -- {}'.format(v, u)
frontier.append(u)
seen.add(v)
graph += '}'
sfdp = Popen(['sfdp', '-Tpng'], stdin = PIPE, stdout = PIPE)
with open('{}.png'.format(name), 'wb') as of:
of.write(sfdp.communicate(input = graph)[0])
@mapio
Copy link
Author

mapio commented Jul 1, 2017

This is the script used to generate the above PNG, that also appears in this tweet; it is based on Graphviz and assumes sfdp layout tool of such package to be in the path.

The tool generates a graph G=(V, E) such that V = {first <= x <= last} and E = {(x, y) : y = x + 1} U {(x, y) : y = 2x}

To run it, just pass the first and last number to consider and the basename of the graph, as in

python graph.py 1 10000 graph

and open  graph.png.

@mazeto
Copy link

mazeto commented Jul 1, 2017

Just works on python 2.7. And here it produces really small images, like 179x173 with the args 1 10000. Any idea why?

@mapio
Copy link
Author

mapio commented Jul 11, 2017

I guess you mean 179x173 pixels, the image size depends on the sfdp tool, part of Graphviz. You can check the manual to see if you can specify a larger size, this Stack Overflow answer could be a good starting point.

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