Fundamentals 3 min read

Exploring Python Lambda Syntax with Prime Number Filtering and Heart‑Shape ASCII Art

The author revisits prime‑number filtering using Python's lambda syntax, rewrites the algorithm with a recursive approach, and then demonstrates a heart‑shaped ASCII art program, highlighting new insights into Python's expressive capabilities and code clarity.

FunTester
FunTester
FunTester
Exploring Python Lambda Syntax with Prime Number Filtering and Heart‑Shape ASCII Art

The author describes learning Python's lambda syntax by re‑implementing a prime‑number filtering algorithm. The approach creates a long list of numbers and recursively filters out multiples using a lambda function, revealing a deeper understanding of Python's concise expression.

Below is the full Python code for the prime‑number filter:

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)

After experimenting with the lambda expression, the author also refactors a one‑line Python program that prints a heart‑shaped pattern. By separating loops and conditionals, the code becomes clearer while still showcasing Python's powerful syntax.

The heart‑shape printing code is presented below:

print'\n'.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)])

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 resulting output is displayed as an image of the heart shape, illustrating the visual effect of the algorithm.

Algorithmpythonlambdaascii artCode TutorialPrime Numbers
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.