user2604985
user2604985

Reputation:

How to put together 4 while loops of triangles to make a "diamond"?

I want to make this "diamond":

********************
*********  *********
********    ********
*******      *******
******        ******
*****          *****
****            ****
***              ***
**                **
*                  *
*                  *
**                **
***              ***
****            ****
*****          *****
******        ******
*******      *******
********    ********
*********  *********
********************

I can make the 4 triangles that make the diamond using while loops:

x = 10
while 0 < x < 11:
    print '%10s' % ('*' * x),
    x = x - 1
    print

x = 0
while x < 11:
    print '%10s' % ('*' * x),
    x = x + 1
    print

x = 10
while 0 < x < 11:
    print '%0s' % ('*' * x),
    x = x - 1
    print

x = 0
while x < 11:
    print '%0s' % ('*' * x),
    x = x + 1
    print

Can I bring together these 4 while loops to make the diamond? Or do I have to do it a different way?

Upvotes: 2

Views: 197

Answers (2)

BioGeek
BioGeek

Reputation: 22827

A very straightforward way is to use two loops:

def diamond(n):
    for i in range(n, 0, -1):
        print '*' * i + (' ' * (n-i) * 2) + '*' * i
    for i in range(1, n+1):
        print '*' * i + (' ' * (n-i) * 2) + '*' * i

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

I suggest you do it using string formatting (you can experiment with the parameters):

a = range(0,20,2)+range(20,-1, -2)

for i in a:
    print '{:*^30}'.format(' '*i)

[OUTPUT]
******************************
**************  **************
*************    *************
************      ************
***********        ***********
**********          **********
*********            *********
********              ********
*******                *******
******                  ******
*****                    *****
******                  ******
*******                *******
********              ********
*********            *********
**********          **********
***********        ***********
************      ************
*************    *************
**************  **************
******************************

What the code above does is it first creates a list a that contains the number of spaces for each of the lines. Then the string formatting prints a line for each element in the list of length 30 (the 30 part of {:*^30} which is centered ^ and padded on either sides with *. Hope that helps.

Or just for fun: one-linered:

for i in range(1,20,2)+range(19,-1, -2):print '{:*^30}'.format(' '*i)

Upvotes: 6

Related Questions