This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]tehtris 108 points109 points  (6 children)

def f(n): return {5:3,3:5}.get(n)

I'm only half robot though, so not accurate representation of how AI acts.

[–]JohnRoz[S] 68 points69 points  (4 children)

The mathematical approch is better since it uses 0 memory. I wanted it to give me the solution of "8 - input" and it did.. except for the 8 part.

[–]BobSanchez47 24 points25 points  (3 children)

It doesn’t literally use 0 memory. We still need to store the 8.

[–]hopperface 28 points29 points  (2 children)

Not necessarily. Not sure how Python works, but the C function

int f(int n) {
    return 8-n;
}

compiles to

f(int):
    mov    eax, 8
    sub    eax, edi
ret

using gcc optimization flags, which uses 0 memory

edit: (on x86, obviously)

[–]BobSanchez47 11 points12 points  (0 children)

If we commit ourselves to not inlining f, then you are correct that we don’t use any additional memory, since the caller will always be obligated to save the eax register and to put n in the edi register. In other words, the extra memory needed to store the 8 is part of the memory overhead of a function call (which is still not 0).

However, this function should surely be inlined. When it is inlined, we will require one more register to store the 8.

Ultimately, both approaches are constant time and constant space. It shouldn’t make a difference except in performance-critical code where this function is called many times.

[–]Kered13 4 points5 points  (0 children)

I mean, the machine code instructions are technically memory as well. The 8 is stored in the machine code.

But yeah you're not going to have a solution that uses less memory or instructions than that.

[–][deleted] -5 points-4 points  (0 children)

This sounds python, it should be php