+ 4
Please explain this code
What is the logic behind this code which enables it to discriminate between odd & even? https://code.sololearn.com/c95wi2FJBmmx/?ref=app
7 Respuestas
+ 9
e = lambda x: True if x == 0 else o(x-1)
o = lambda x: not e(x)
e(8//2) is the same as e(4)
- e(4)
x == 0? False
=> return o(3)
- o(3)
return not e(3)
temporary result: return not(e(3))
- e(3)
x == 0? False
=> return o(2)
- o(2)
return not e(2)
temporary result: return not(not(e(2)))
- e(2)
x == 0? False
=> return o(1)
- o(1)
return not e(1)
temporary result: return not(not(not(e(1))))
- e(1)
x == 0? False
=> return o(0)
- o(0)
return not e(0)
temporary result: return not(not(not(not(e(0)))))
- e(0)
x == 0? True
=> return True
result: return not(not(not(not(True)))) = return True
+ 9
you must keep in mind that the result that will finally be returned is e(4). So it's obvious that it will not be directly "True", because 4!=0
Then, it will be o(x-1), o(3)
ok, but o(3) has no value yet ...
it's just: not e(3)
ok, so what's e(3), it's not 0, etc...
For each iteration, the code is actually reversing once the True given by e(x) for x=0
so :
x bool
0 True
1 False
2 True
3 False
4 True,
etc...
+ 8
Nice explanation Anna !
And a funny code Rik !
+ 7
Happy you got it, thanks for sharing this interesting twin-recursive function 😊
+ 4
I feel like dumb & dumber here.
Anna's explanation shows the code iterating until it reaches a True value, but does not explain (to me, ie: I don't understand) how the code ascertains the end result of 'even' or 'odd'.
Is it a boolean value based on the number of iterations?
+ 4
The penny has dropped. Thanks heaps
+ 3
Not my code, it was written by 4G3N7. I thought that info was in the original post - my mistake.
Thanks for your responses