Calling J from Python
greg
greg at cosc.canterbury.ac.nz
Sat Feb 10 04:23:14 EST 2007
Alexander Schmolck wrote:
> how would you code a program that gives the following
> output ('skewed' sierpinski-triangle) in python?
>
>
> *
> **
> * *
> ****
> * *
> ** **
> * * * *
> ********
> * *
> ** **
> * * * *
> **** ****
> * * * *
> ** ** ** **
> * * * * * * * *
> ****************
###############################################################
def print_sierpinski(order):
size = 4 * 2 ** order
buffer = [size * [" "] for i in range(size)]
put_sierpinski(buffer, size, 0, 0)
for line in buffer:
print "".join(line)
def put_sierpinski(buffer, size, x, y):
if size == 4:
put_triangle(buffer, size, x, y)
else:
size2 = size / 2
put_sierpinski(buffer, size2, x, y)
put_sierpinski(buffer, size2, x, y + size2)
put_sierpinski(buffer, size2, x + size2, y + size2)
def put_triangle(buffer, size, x, y):
for i in range(3):
buffer[y + i][x] = buffer[y + i][x + i] = "*"
for i in range(4):
buffer[y + 3][x + i] = "*"
print_sierpinski(2)
###############################################################
By making the recursion explicit, I think this brings out the
self-similarity better than any of the other solutions posted,
which are very clever but not what I would call "lucid".
--
Greg
More information about the Python-list
mailing list