Editorial for Lyndon's Golf Contest 1 P3 - Boolean (Buffed)


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: Dingledooper

42 bytes

One possible way to solve this problem is to output true if the number of nots and trues combined is odd, and false otherwise. Because not, true, and false are the only possible tokens, it is easy to calculate this by counting the number of ts in the entire string, \bmod 2. Rather than using an if statement to determine what to output, a shorter method would be to store the two outputs in a list, and access the correct one by its index. This gives us a 45-byte solution:

print(['false','true'][input().count('t')%2])

Shorter yet, we can convert the integer to a boolean (True or False) via a comparison, cast it to a string, and then convert it to lowercase. This trick of reusing Python's built-in boolean literals brings our solution down to 42 bytes:

print(str(input().count('t')%2>0).lower())

38 bytes

In order to go lower, we must find a way to convert the given input into something useful, without adding too much complexity to our program. The len() function is a perfect candidate for this, as it not only is short, but maps every unique input to a unique integer. Notice first that the length of the input can only come in two forms: 4n and 4n+1, for some n \ge 0. Equivalently, if the length is x, it must hold that x \bmod 8 \in \{0, 1, 4, 5\}. Then, notice that the answer is true iff x \bmod 8 \in \{1, 4\}. From this information, we can construct a specialized formula that happens to solve our original problem. x%8%5>0 and 0<x%8<5, for example, are both valid ways to determine the input's truthiness. With this in mind, we obtain a 38-byte solution:

print(str(len(input())%8%5>0).lower())

37 bytes

The reduction to 37 bytes is a simple, yet sneaky trick. If we instead consider -x \bmod 8, the possible values for x are -x \bmod 8 \in \{0, 3, 4, 7\}, and the answer is true iff -x \bmod 8 \in \{4, 7\}. From this, it becomes clear that a single byte can be saved by shortening the formula to -x%8>3, leading to our final solution:

print(str(-len(input())%8>3).lower())

Comments

There are no comments at the moment.