Tuesday, 26 March 2024

Python pattern challenge - Day 8

 

def gen_tri(size):

    for i in range(0, size//2 + 1):

        yield ' ' * i + '*' * (size - 2*i) + ' ' * i

def print_heart(size):

    size = 2*size + 1

    for i in reversed(list(gen_tri(size//2))):

        print(i, i)

    for i in gen_tri(size):

        print(i)

print_heart(4)


Explanation: 

This Python code defines two functions: gen_tri(size) and print_heart(size), and then it calls print_heart(4).

Here's what each part does:

gen_tri(size) Function:

This function generates lines for a triangle pattern.
It takes one parameter size, which represents the width of the base of the triangle.
It uses a loop to iterate over the range from 0 to size//2 + 1. This ensures that the triangle will have a height equal to half of the base plus one.
For each iteration, it yields a string consisting of spaces and asterisks (' ' and '*') to form the triangle shape. The number of spaces (' ') before and after the asterisks decreases as i increases, and the number of asterisks increases accordingly.
print_heart(size) Function:

This function prints a heart shape composed of two triangles.
It takes one parameter size, which represents the size of the heart.
Inside this function, size is modified to ensure symmetry and compatibility with the gen_tri function.
It first prints the upper triangle of the heart by iterating in reverse over the lines generated by gen_tri for half of the specified size.
Then, it prints the lower triangle of the heart by iterating over the lines generated by gen_tri for the other half of the specified size.
print_heart(4) Call:

This line calls the print_heart function with size equal to 4.
It will print a heart shape where the base of the triangle in each half has a width of 4 characters.
Overall, this code generates and prints a heart shape made up of two triangles, with a specified size.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (363) Python Quiz (25) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses