Another challenge

Another dreaded reverse challenge! I don’t like them but this one was quite easy. The challenge was to write a function called imagine that takes 4 arguments (a, b, c, d) and returns two values.

Input:
a: 5
b: 0
c: 3
d: 0
Expected Output:
[15, 0]
As always there were ten test cases, and the way the answers came out, together with the name of the function, led me to think this was regarding complex numbers. Would it be as simple as interpreting the input as two complex numbers, and return the product as output? It wouldn’t be that simple, wouldn’t it?
def imagine(a, b, c, d):
    x = complex(a, b)
    y = complex(c, d)
    r = x * y
    return r.real, r.imag
Why yes! That’s it. Problem solved! Except of course, for the #### challenge in codefights that the code is the shortest amount of (non whitespace) characters possible. This solution, with 72 characters, was nearly twice as long as the 39 characters for the shortest Python solution. My first thought was to introduce some abbreviations and speed things up:
def imagine(a, b, c, d):
    f = complex
    r = f(a, b) * f(c, d)
    return r.real, r.imag
 Well, that reduces a full six characters. Then I realized: complex products are basically matrix multiplication, and not exactly rocket science. Why bother calling the complex function if you can operate straight on the real and imaginary components?
def imagine(a, b, c, d):
    return a*c - b*d, a*d + b*c
This does exactly the same, and is only two characters longer than the best entry (39). The observant student will notice that the result is calculated in a single line though. And that means that we can use a lambda abomination to get even shorter (and harder to read) code:
imagine = lambda a,b,c,d:(a*c - b*d, a*d + b*c)
The parens are required because the lambda function takes multiple arguments. So, at the price of destroying the little piece of readability that was left, we got at what is the shortest entry for Python code: 39 characters.
I still think my first attempt was much, much better code.

Leave a comment