My friend challenged me to find the shortest solution to a certain Leetcode-style problem in Python. They were generous enough to let me use whitespac

Any Python program fits in 30 characters* | purplesyringa's blog

submited by
Style Pass
2024-11-16 22:00:02

My friend challenged me to find the shortest solution to a certain Leetcode-style problem in Python. They were generous enough to let me use whitespace for free, so that the code stays readable. So that’s exactly what we’ll abuse to encode any Python program in 30 bytes, ignoring whitespace.

Bits We can encode arbitrary data in a string by only using whitespace. For example, we could encode 0 bits as spaces and 1 bits as tabs. Now you just have to decode this.

As you start implementing the decoder, it immediately becomes clear that this approach requires about 50 characters at minimum. You can use c % 2 for c in b"..." to extract individual bits, then you need to merge bits by using str and concatenating then with "".join(...), then you to parse the bits with int.to_bytes(...), and finally call exec. We need to find another solution.

Characters What if we didn’t go from characters to bits and then back? What if instead, we mapped each whitespace character to its own non-whitespace character and then evaluated that?exec( "[whitespace...]" .replace(" ", "A") .replace("\t", "B") .replace("\v", "C") .replace("\f", "D") ... )

Leave a Comment