import sys from math import sqrt n = int(sys.argv[1]) if len(sys.argv) > 1 else 10 sin60 = sqrt(3) / 2 def make_triangle(x, y, s, n, output): """Draw an nth approximation to Sierpinski's gasket, with lower-left corner at (x,y), and size s x s. Writes Postscript commands to the the standard output to do the drawing.""" if n == 0: print("{0:.2f} {1:.2f} moveto " "{2:.2f} 0 rlineto " "-{3:.2f} {4:.2f} rlineto " "closepath fill" .format(x, y, s, s/2, s*sin60), file=output) else: make_triangle(x, y, s/2, n - 1, output) make_triangle(x + s/2, y, s/2, n - 1, output) make_triangle(x + s/4, y + sin60*s/2, s/2, n-1, output) def draw_gasket(n, file=sys.stdout): print("%!", file=file) make_triangle(100, 100, 400, n, output=file) print("showpage", file=file)