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):




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.


Post a Comment

Popular Posts


AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (87) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (740) Python Coding Challenge (188) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)


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