Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyramid of asterisks program in Python

I've written a program in C++ that displays a pyramid of asterisk (see below) and now I'd like to see how it's done in Python but it's not as easy as I'd thought it would be.

Has anyone tried this and if so could you show me code that would help out?

Thanks in advance.

       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************
like image 667
jimmyc3po Avatar asked Feb 06 '11 03:02

jimmyc3po


2 Answers

def pyramid(rows=8):
    for i in range(rows):
        print ' '*(rows-i-1) + '*'*(2*i+1)

pyramid(8)
       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************

pyramid(12)
           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
***********************
like image 85
Hugh Bothwell Avatar answered Oct 06 '22 00:10

Hugh Bothwell


Or you could try:

def pyramid(size=8):
    for i in range(size):
        row = '*'*(2*i+1)
        print row.center(2*size)
like image 39
kleytont Avatar answered Oct 06 '22 00:10

kleytont