Exploring Python Lambdas: Prime Filtering and a Heart‑Shaped Print
The author revisits a prime‑number filter using Python's lambda syntax, then refactors a one‑line heart‑shape printer into clearer loops, showcasing how lambda expressions and list comprehensions can simplify mathematical visualizations while deepening understanding of Python's expressive power.
While learning Python's lambda syntax, the author rewrote a prime‑number filtering algorithm originally based on a long‑array and recursive division approach. The new implementation creates a range of numbers, then recursively filters out multiples using a lambda that returns True for the current divisor and otherwise checks that the candidate is not divisible by that divisor.
i = 0
a = range(2, 20)
def test(sss):
global i
if i >= len(sss):
return sss
re = list(filter(lambda x: True if (a[i] == x) else (x % a[i] != 0), sss))
i += 1
return test(re)
c = test(a)
print(c)Running this script prints the list of prime numbers between 2 and 19.
The article then presents a classic one‑liner that prints a heart shape made of the word "Love". To improve readability, the author expands the one‑liner into explicit for loops, separating the iteration and conditional logic.
# Compact one‑liner version
print('
'.join([''.join(['Love'[(x - y) % 4] 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)]))
# Expanded version for clarity
for y in range(15, -15, -1):
line = []
for x in range(-30, 30):
if ((x * 0.05) ** 2 + (y * 0.1) ** 2 - 1) ** 3 - (x * 0.05) ** 2 * (y * 0.1) ** 3 <= 0:
line.append('Love'[(x - y) % 4])
else:
line.append(' ')
l = ''.join(line)
print(l)The expanded code makes the mathematical condition and the character selection explicit, helping readers see how the heart shape emerges from the inequality and how the modulo operation cycles through the letters of "Love".
An image of the resulting heart‑shaped output is included to illustrate the visual result.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
