Python – Print Heart Pattern
Last Updated :
05 Aug, 2022
Given an even integer input, the task is to write a Python program to print a heart using loops and mathematical formulations.
Example :
For n = 8
* * * *
* * *
* *
* G F G *
* *
* *
* *
*
For n = 14
* * * *
* * * *
* * * *
* * *
* *
* G F G *
* *
* *
* *
* *
* *
* *
*
Approach :
The following steps are used :
- Form the worksheet of n X n+1 using two loops.
- Apply the if-else conditions for printing stars.
- Apply the if-else conditions for printing text “GFG”.
- Apply else condition for rest spaces.
Note: The value of n must be greater than 8
Below is the implementation of the above approach :
Python3
n = 8
m = n + 1
for i in range (n / / 2 - 1 ):
for j in range (m):
if i = = n / / 2 - 2 and (j = = 0 or j = = m - 1 ):
print ( "*" , end = " " )
elif j < = m / / 2 and ((i + j = = n / / 2 - 3 and j < = m / / 4 ) \
or (j - i = = m / / 2 - n / / 2 + 3 and j > m / / 4 )):
print ( "*" , end = " " )
elif j > m / / 2 and ((i + j = = n / / 2 - 3 + m / / 2 and j < 3 * m / / 4 ) \
or (j - i = = m / / 2 - n / / 2 + 3 + m / / 2 and j > = 3 * m / / 4 )):
print ( "*" , end = " " )
else :
print ( " " , end = " " )
print ()
for i in range (n / / 2 - 1 , n):
for j in range (m):
if (i - j = = n / / 2 - 1 ) or (i + j = = n - 1 + m / / 2 ):
print ( '*' , end = " " )
elif i = = n / / 2 - 1 :
if j = = m / / 2 - 1 or j = = m / / 2 + 1 :
print ( 'G' , end = " " )
elif j = = m / / 2 :
print ( 'F' , end = " " )
else :
print ( ' ' , end = " " )
else :
print ( ' ' , end = " " )
print ()
|
Output:
* * * *
* * * *
* * * *
* * *
* *
* G F G *
* *
* *
* *
* *
* *
* *
*
Time complexity: O(n2) for given input n
Auxiliary Space: O(1)
Please Login to comment...