I was asked a question about why the following code gives the following result:
def find(j):
if(j>1):
j=find(j//10)-(j%10)
print(j)
else:
j=0
return j
i=122
k=find(i)
RESULT:
-2
-4
Why that particular result? Here is what I have so far:
def find(j)
– defying function find with j being an argument
if j is greater than 1, the argument j within find function is divided by 10
122 % 10 = 2
print (j)
– calls function find to display
From this point on, I am struggling. Why -2 and where is -4 coming from?
CodePudding user response:
The answer is likely due to a Python version difference. Modern versions of Python treat /
as float division even if the operands are ints. Python 2 did the equivalent of //
(int division) if the operands were ints.
If I modify your code to use int division (which seems like it was probably the intent, since it also uses the %
operator) then I get the expected results:
>>> def find(j):
... if(j>1):
... j=find(j/10)-(j%10)
... print(j)
... else:
... j=0
... return j
...
>>> find(122)
-1.22
-3.419999999999999
-5.419999999999999
-5.419999999999999
>>> def find(j):
... if(j>1):
... j=find(j//10)-(j%10)
... print(j)
... else:
... j=0
... return j
...
>>> find(122)
-2
-4
-4
CodePudding user response:
A version of your code modified to explain what it's doing and why follows:
def find(j):
if(j>1):
find_result = find(j//10)
new_j = find_result - (j%10)
print("j == %r; find(%r) => %r; find(%r) - %r => %r" % (
j, (j//10), find_result, (j//10), j % 10, new_j))
j = new_j
else:
j=0
return j
i=122
k=find(i)
...its output is as follows:
j == 12; find(1) => 0; find(1) - 2 => -2
j == 122; find(12) => -2; find(12) - 2 => -4
So: First, you start with j=122
. It thus calculates find(12)
and subtracts 2
from the result. So before we know what that will do, we need find(12)
.
find(12)
checks if j > 1
. Because 1
is not > 1
, this is false, so it returns 0
. The caller than subtracts 2 from this, getting -2
, which it prints.
Then, find(122)
takes this result of -2
, and subtracts an additional 2
from it, so it gets -4
.