Saturday, February 9, 2019

Printing Shapes

The image below contains some question for printing different shapes.


Solutions:

Code for Question 11:

width = int(input("Enter width of the box: "))
height = int(input("Enter height of the box: "))
for i in range(height):
for j in range(width):
if i == 0 or i == height-1:
print(end="*")
elif j > 0 and j < width-1:
print(end=" ")
else:
print(end="*")
print()
view raw BoxPattern.py hosted with ❤ by GitHub

Alternative Method:

width = int(input("Enter width of the box: "))
height = int(input("Enter height of the box: "))
print("*"*width)
for i in range(height-2):
print("*" + " "*(width-2) + "*")
print("*"*width)
view raw BoxPattern2.py hosted with ❤ by GitHub

Code for Question 12:

height = int(input("Enter height of the triangle: "))
for i in range(1,height+1):
for j in range(i):
print(end="*")
print()

Alternative Method:

height = int(input("Enter height of the triangle: "))
for i in range(1,height+1):
print("*"*i)

Code for Question 13:

height = int(input("Enter height of the triangle: "))
for i in range(height,0,-1):
for j in range(i):
print(end="*")
print()

Alternative Method:

height = int(input("Enter height of the triangle: "))
for i in range(height,0,-1):
print("*"*i)

Code for Question 14:

import math
height = int(input("Enter height of the triangle: "))
mid = math.ceil(height/2)
for i in range(1,height+1):
if i > mid:
m = i-2*(i-mid)
else:
m = i
n = 2*m-1
for j in range(mid-m):
print(end=" ")
for j in range(n):
print(end="*")
print()

Alternative Method:

import math
height = int(input("Enter height of the triangle: "))
mid = math.ceil(height/2)
for i in range(1,height+1):
if i > mid:
m = i-2*(i-mid)
else:
m = i
n = 2*m-1
print(" "*(mid-m), end="")
print("*"*n)

No comments: