Can somebody explain, how this python code works which prints the heart in Instagram

Viewed 46

I found this code on google's instagram page and I can't understand what it is doing to print that amazing heart. Can somebody just make this easy for me to grasp ?

print('\n'.join([''.join([('Engineer '[(x-y)%8] 
     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)]))

1 Answers

Formatted with black, the code is

print(
    "\n".join(
        [
            "".join(
                [
                    (
                        "Engineer "[(x - y) % 8]
                        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)
        ]
    )
)

It's effectively solving where the inequality

((x * 0.05) ** 2 + (y * 0.1) ** 2 - 1) ** 3 - (x * 0.05) ** 2 * (y * 0.1) ** 3 <= 0

is true for x from -30 to +30 and y from -15 to +15 (in reverse order), which has been carefully designed to form a heart.

Where it is true, the letters from the word "Engineer" are printed, and where not, a space.

A simpler, but not as "cute" way, to get the same result, would be

for y in range(15, -15, -1):
    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:
            print("Engineer"[(x - y) % 8], end="")
        else:
            print(" ", end="")
    print()  # just print newline
Related