SQL_rookie
SQL_rookie

Reputation: 153

Please help me understand an unexpected result when doing arithmetic with functions

How is the answer 1?

Bit confused with this, can someone explain why for beta y - x is 2 - 3 rather than 3 - 2?

What does alpha(2, 3) evaluate to:

def alpha(x, y):
    return x + beta(y, x)

def beta(x, y):    
    return y - x        # [1]

Upvotes: 1

Views: 88

Answers (6)

Matthew Merlene
Matthew Merlene

Reputation: 66

   alpha(2,3)
-> 2+beta(3,2)
-> 2+(2-3)
-> 2+2-3 = 4-3 = 1

Upvotes: 0

Konrad Talik
Konrad Talik

Reputation: 916

You are passing y as x and x as y.

In that case alpha(2, 3) means 2 + beta(3, 2) which evaluates to 2 + 2 - 3 which is 1.

Upvotes: 0

Marc B
Marc B

Reputation: 360562

The function arguments swap places:

return x + beta(y, x)    <-- y, x
def beta(x, y):          <-- x, y

So function call beta(2,3) executes return 2 - 3

Upvotes: 0

BartoszKP
BartoszKP

Reputation: 35891

alpha(2,3)

results in the following code being executed:

return 2 + beta(3,2)   # (*)

The beta(3,2) call in turn results in:

 return 2 - 3

which gives -1, so in (*) you have 2 + -1, which is 1.

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121236

You are getting confused by the names in alpha; it calls beta() with the arguments swapped.

Pay close attention to the x and y in alpha(). If it helps, replace the arguments with longer names:

def alpha(first, second):
    return first + beta(second, first)

Filling in the values everywhere gives you:

alpha(2, 3)
-> 2 + beta(3, 2)
-> 2 + (2 - 3)
-> 2 + -1
-> 1

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

Alpha evaluates:

x-beta(y,x)=x+x-y=2*x-y.

Mind you swapped the parameters of beta in the call.

Upvotes: 0

Related Questions