MutantMahesh's Blog

Seeking to know.

Dec 12, 2021 - 2 minute read - Python Star Patterns Algorithm

Print the different triangle star patterns in python:

Pattern 1: Print the following triangle star pattern

1. Take an integer input from user = n
2. Print the triangle stars starting from one star * up to the n lines of stars, with each line the number of stars will increase
*
**
***
****
*****

Solution:

n = int(input("Enter a number: "))
for i in range(n):
print('*' * (i + 1))

Pattern 2: Print the following triangle star pattern

1. Take an integer input from user = n
2. Print the stars starting from one star * up to the n lines of stars, with each line the number of stars will increase, but the star pattern will start from end of the line
*
**
***
****
*****

Solution:

n = int(input("Enter a number: "))
# Create one filler list with white spaces with n elements
filler = [' '] * n
for index in range(n):
filler[-(index + 1)] = '*'
for i in range(n):
print(filler[i], end = '')
print('')

Pattern 3: Print the following triangle star pattern

1. Take an integer input from user = n
2. Print the stars in triangle shap, the starting point of stars will be from middle of the line
*
***
*****
*******
n = int(input("Enter a number: "))
# Convert the number to Odd if even number is provided.
if (n % 2 == 0):
n = n + 1
# Create one filler list with white spaces with n elements
filler = [' '] * n
middle = ((n // 2) + 1)
filler[-middle] = '*'
for i in range(middle - 1):
print(''.join(filler))
filler[-middle - (i+1)] = '*'
filler[-middle + (i+1)] = '*'
print(''.join(filler), end = "")

Pattern 4: Print the following triangle star pattern

*
***
*****
*******
*****
***
*
1. Take an integer input from user = n
2. Print the stars in diamond shap
n = int(input("Enter a number: "))
# Convert it to odd number, if even number is given
if (n % 2 == 0):
n += 1
# Create one filler list with white spaces with n elements
filler = [' '] * n
middle = (n // 2) + 1
filler[-middle] = '*'
for i in range(middle - 1):
print(''.join(filler))
filler[-middle - (i+1)] = '*'
filler[-middle + (i+1)] = '*'
for i in reversed(range(middle)):
print(''.join(filler))
filler[-middle - i] = ' '
filler[-middle + i] = ' '