Welcome, guest | Sign In | My Account | Store | Cart

Given the following function header:

def triangles(n):

If n for example is 5, then the drawing would be like this:

    *
  * * *
* * * * *
  * * *
    *
Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def triangles(n):
    if not n & 1:
        raise ValueError('n must be odd')
    print_diamond(0, n, n >> 1)

def print_diamond(start, stop, midpoint):
    if start < stop:
        if start <= midpoint:
            print('  ' * (midpoint - start) + '* ' * ((start << 1) + 1))
        else:
            print('  ' * (start - midpoint) + '* ' * ((stop - start << 1) - 1))
        print_diamond(start + 1, stop, midpoint)
Created by Stephen Chappell on Fri, 7 Nov 2014 (MIT)
Python recipes (4591)
Stephen Chappell's recipes (233)

Required Modules

  • (none specified)

Other Information and Tasks