1

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!

3
  • you can't because integers are immutables in python Commented Mar 16, 2013 at 21:53
  • 1
    By the way, there's no need for parentheses around expressions (in your if and while statements). Commented Mar 16, 2013 at 21:57
  • @thkang Integers being immutable has nothing to do with it. func(a) can never change what the local name a refers to in the calling scope, regardless of what kind of value that name refers to. Commented Mar 16, 2013 at 22:13

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, this is how I originally had it, but my teacher is always saying we should try to split out our functions more.
@h1h1: What your teacher is saying is a good general guideline. It's just knowing when to stop that can be a little tricky at times, but that comes with experience.
2

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.