Skip to content

Instantly share code, notes, and snippets.

@mapio mapio/graph.png

Last active Jul 23, 2020
What would you like to do?
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)
graph += '}'
sfdp = Popen(['sfdp', '-Tpng'], stdin = PIPE, stdout = PIPE)
with open('{}.png'.format(name), 'wb') as of:
of.write(sfdp.communicate(input = graph)[0])

This comment has been minimized.

Copy link
Owner 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 1 10000 graph

and open  graph.png.


This comment has been minimized.

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?


This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.