Show Your Love with This Python One-Liner! Printing a Heart with Name (ASCII Art)

4.5/5 - (2 votes)

I just stumbled on this beautiful Python one-liner submitted by GitHub user ZenOfTech to our GitHub repository one-liner collection:

love='ILoveFinxter';print('\n'.join([''.join([(love[(x-y)%len(love)] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ') for x in range(-30,30 )]) for y in range(15, -15, -1)]))

The beautiful output:

                erILoveFi           inxterILo               
            nxterILoveFinxter   veFinxterILoveFin           

You can easily change it by adding the name of your love, say 'Alice':

love='Alice';print('\n'.join([''.join([(love[(x-y)%len(love)] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ') for x in range(-30,30 )]) for y in range(15, -15, -1)]))

The output:

                eAliceAli           eAliceAli               
            liceAliceAliceAli   liceAliceAliceAli           

How does the code work?

First, I’d recommend you check out our article and video on list comprehension if you don’t yet know what this means:

πŸ’‘ Recommended: Python List Comprehension [Ultimate Guide]

How Does It Work?

This Python code prints a heart shape with the text 'Alice' repeated within the shape. Let’s break down the code to understand how it works:

  1. love = 'Alice': Assigns the string 'Alice' to the variable love.
  2. for y in range(15, -15, -1): Iterates through the numbers from 15 to -14, with a step of -1. This loop controls the vertical position (rows) of the heart shape.
  3. for x in range(-30, 30): Iterates through the numbers from -30 to 29. This loop controls the horizontal position (columns) of the heart shape.
  4. The condition ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 checks whether the current (x, y) coordinate is inside the heart shape or not.
  5. If the condition is True, (love[(x-y)%len(love)]) selects a character from the string 'Alice' based on the result of (x-y)%len(love). This creates a repeating pattern of the string 'Alice' inside the heart shape.
  6. If the condition is False, a space character (' ') is added, which represents the area outside the heart shape.
  7. ''.join([...]) joins the characters from the inner loop (step 3) into a single string for each row.
  8. '\n'.join([...]) joins the strings from the outer loop (step 2) using newline characters ('\n') to separate each row, creating the final output string.
  9. print( ... ) prints the final output.

Checking The Heart Shape – The Ellipse Math β™₯️

Let’s dive deeper into step number 4, i.e., the condition formula to check if a given coordinate is in the heart shape, or not:

The condition ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 is an implicit function that describes the heart shape in a 2D plane. Let’s break down the mathematical expression:

  1. (x*0.05) and (y*0.1): The coordinates (x, y) are scaled down by factors of 0.05 and 0.1, respectively. This scaling is done to make the heart shape fit nicely within the given coordinate ranges (-30 to 29 for x, and 15 to -14 for y).
  2. ((x*0.05)**2+(y*0.1)**2-1)**3: This part of the expression is a modified form of the equation for an ellipse. The standard equation for an ellipse is (x/a)^2 + (y/b)^2 = 1, where a and b are the semi-major and semi-minor axes, respectively. Here, the ellipse is slightly modified by raising the entire expression to the power of 3.
  3. -(x*0.05)**2*(y*0.1)**3: This term is subtracted from the modified ellipse equation to distort the ellipse and create the heart shape. The product of (x*0.05)^2 and (y*0.1)^3 creates a “dent” at the top of the ellipse, forming the two lobes of the heart shape.
  4. Finally, the inequality <=0 checks whether a given (x, y) coordinate lies inside or outside the heart shape. If the value of the expression is less than or equal to 0, it means that the point is inside the heart shape, and a character from the 'Alice' string is chosen. If the value is greater than 0, the point is outside the heart shape, and a space character is used instead.

To summarize, the condition ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 is a mathematical equation that implicitly defines a heart shape.

The code iterates through the 2D coordinate space and checks if each coordinate lies inside or outside the heart shape using this condition, and then it selects either a character from the 'Alice' string or a space character accordingly.

The Equation of the Heart, Derived from the Ellipse

If you like one-liners, you’ll love my book! πŸ‘‡

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

Also, if you’re a Finxter premium member, check out our course on Python One-Liner tricks: