jevans
jevans

Reputation: 399

Draw Unfilled squares & triangles in Python

I have the code to draw a filled square:

for i in range(0,n):
    print(n*"*")

Which prints (obviously dependent on the value of n):

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

And a filled triangle:

for i in range(1,n+1):
    print((n-(n-i)) * "*")

Which prints (also dependent on n):

*
**
***
****

But I'm unsure how to adapt these to draw a square like this:

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

Or a triangle like this:

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

So that each missing asterisk is replaced by a blank character (i.e. a space) The main context is irrelevant. I just need to be able to draw these four things depending on a users input.

Upvotes: 0

Views: 8881

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

For Triangle:

In [26]: def hollow_tri(n):
   ....:     print "*"
   ....:     for i in xrange(2,n):
   ....:         print "*{0}*".format(" "*(i-2))
   ....:     print "*"*n
   ....:     

In [27]: hollow_tri(8)
*
**
* *
*  *
*   *
*    *
*     *
********

In [28]: hollow_tri(4)
*
**
* *
****

For Square:

In [29]: def hollow_square(n):
    print "*"*n
    for i in xrange(2,n):
        print "*{0}*".format(" "*(n-2))
    print "*"*n
   ....:     



In [30]: hollow_square(4)
****
*  *
*  *
****




In [31]: hollow_square(8)
********
*      *
*      *
*      *
*      *
*      *
*      *
********

Upvotes: 1

Ecliptica
Ecliptica

Reputation: 830

For the square:

import sys

for i in range(n):
    for j in range(n):
        if i == 0 or j == 0 or i == n - 1 or j == n - 1:
            sys.stdout.write("*")
        else:
            sys.stdout.write(" ")
    print("")

Output for n = 5:

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

For the triangle:

import sys

for i in range(n):
    for j in range(i+1):
        if j == 0 or j == i or i == n - 1:
            sys.stdout.write("*")
        else:
            sys.stdout.write(" ")
    print("")

Output for n = 5:

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

Note that I used sys.stdout.write instead of print to avoid extra spaces or newlines.

Upvotes: 3

0x90
0x90

Reputation: 40982

Here is the solution for the triangle which is a bit trickier, the rectangular you can figure out by yourself.

>>> for i in range(0,n+2):
        if i in [0,n+1]:
                print (i+1)*"*"
        else:
                print("*" + (" "*(n-1-(n-i))) + "*")


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

Upvotes: 2

Related Questions