Introduction
Pattern problems are one of the most asked questions in technical interviews or college exams. Patterns are basically repeated series or sequences. There are various types of patterns like stars, pyramids, diamonds, rectangles, etc. In this article, we will try to cover most of them. Most importantly, we shall try to get the intuition behind solving any pattern problem.
Recommended topics, Floor Division in Python, and Convert String to List Python
Pyramid Patterns
There can be a variety of pyramid patterns. However, there are certain common things that we can keep in mind while solving pyramid pattern problems.
- We can use an outer loop for the number of rows.
- We can use the inner loop for the number of columns.
- Carefully observe the spacings, whether there is an odd number of gaps or even number of gaps.
Half Pyramid Of Stars
Pattern:
*
**
***
****
*****
Code:
for i in range(1,6):
for j in range(1,i+1):
print("*",end="") // to print in a single line
print() // to change the line
Explanation:
- Firstly we should try to see if there is any kind of pattern or sequence in the given star pattern.
- We see that there are five rows, and for ith row, there are i number of * in that row.
- We, therefore, need an outer loop to iterate for five times, as we have five rows.
- We have an inner loop that prints the *, i number of times. So for every ith iteration of the outer loop, we run an inner loop i number of times.
Read More, leap year program in python
Inverted Pyramid Involving Numbers
Pattern:
55555
4444
333
22
1
Code:
for i in range(5,0,-1):
for j in range(0,i):
print(i,end="")
print()
Explanation:
- The outer loop runs five times, i.e., for i= 5, 4, 3,2,1.
- For every i starting from 5 and going down to 1, we need an inner loop that runs exactly i number of times. Example: for i=5, the inner loop will have j values as 0,1,2,3,4. Hence it will iterate five times, which is the value of i.
- In every iteration, we print the value of i.
Full Pyramid
Pattern:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Code:
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
Also see, Fibonacci Series in Python