• Coding
  • [Exercise] a function composition question

This one is meant in jest. It works 50% of the time. The question is, using probabilistic methods, is it possible to do better than 50%?
import random

def f(n):
    return n * random.choice((-1,1))
raja wroteThis one is meant in jest. It works 50% of the time. The question is, using probabilistic methods, is it possible to do better than 50%?
import random

def f(n):
    return n * random.choice((-1,1))
Define "probabilistic method".
In particular, if we attach to any of the deterministic methods an unused "random generation" statement, does it turn them probabilistic.
Hmmm, well I'd say a good way to think about it would be, don't use any if/switch/etc... statements whose outcomes are deterministic(I'm not going for a definition of "probabilistic" or anything, just was wondering if a similar approach to the code above could be right more than 50% of the time, kinda thinking out loud).
PS: Here is a simpler version(no recursion) of Arithma's solution:
def f(n):
    offset = 1 if n > 0 else (-1 if n != 0 else 0)
    if n % 2 == 1:
        return n + offset
    else:
        return - (n-offset)
Result:
>>> for i in range(-10, 11):
...  print i, "=>", f(f(i))
... 
-10 => 10
-9 => 9
-8 => 8
-7 => 7
-6 => 6
-5 => 5
-4 => 4
-3 => 3
-2 => 2
-1 => 1
0 => 0
1 => -1
2 => -2
3 => -3
4 => -4
5 => -5
6 => -6
7 => -7
8 => -8
9 => -9
10 => -10
>>> 
9 months later
I don't think the function involve even numbers.
f(n) = 0n;
I win?
Johnaudi wrote
f(n) = 0n;
I win?
Your f(f(-5))=0 != -(-5)