h1h1
h1h1

Reputation: 790

Python - Implementing Functions

I am creating a function to check x is greater than y, and if not it switches the two values and returns them.

def xGreater(x, y):
    if(y > x):
        x, y = y, x
    return x, y

My query is what is the best way to go about using this function within another function, my current code is the following:

def gcd(x, y):
    x , y = xGreater(x, y)
    r = x % y
    while(r != 0):
        x, y = y, r
        r = x % y
    return y

Can I not simply call xGreater(x, y) to alter the values of x and y, without the x, y = in front? Or does this only work when there is a single variable being returned. Thanks!

Upvotes: 1

Views: 292

Answers (3)

Dan
Dan

Reputation: 1179

NPE has a better solution but I'm bored and wanted to write some bit hacks

def gcd(x,y):
    minVal = y ^((x ^ y) & -(x < y))

    if ( minVal == y ):
        y = x ^ y  # Swapping values without a intermediate variable
        y = y ^ y  # This is highly inefficient to use.
        x = x ^ y  # But still kinda cool.

   return x % y

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

No, integers are immutable. But hey, you can cut down on one instance of tuple packing/unpacking:

def xGreater(x, y):
    return (y, x) if y > x else (x, y)

Upvotes: 2

NPE
NPE

Reputation: 500883

Can I not simply call xGreater(x, y) to alter the values of x and y, without the x, y = in front?

I am afraid you can't, since x and y are immutable and are passed into xGreater() by value.

It can be done in some special cases (for example, if x and y were two lists), but not generally.

To be totally honest, I'd get rid of xGreater() and just do the swap in gcd():

def gcd(x, y):
    if y > x:
        x, y = y, x
    r = x % y
    ...

I personally find the code more readable this way.

Upvotes: 3

Related Questions