Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'while' with an integer mean in Python and how does this GCD code work?

I found this greatest common denominator code:

def gcd(x,y):
    while y:
        x, y = y, x % y
    return x

I cannot understand what we mean by while y as y is an integer. How does it work? Furthermore, what does the line x, y = y, x % y add to the code?

like image 834
Mike Boomer Avatar asked Aug 31 '11 00:08

Mike Boomer


1 Answers

For while, read this: http://docs.python.org/reference/compound_stmts.html#the-while-statement

It says "This repeatedly tests the expression and, if it is true, executes the first suite;"

Now the question is: What's True?

Read this: http://docs.python.org/library/functions.html#bool

Then read this: http://docs.python.org/library/stdtypes.html#truth-value-testing

Non-zero values are True. Zero is false.

What does the line "x, y=y, x%y" add to the code?

Makes precious little sense as a question. "add to the code"? What? What part is confusing?

Read this: http://docs.python.org/reference/simple_stmts.html#assignment-statements

"If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets."

For the integer '%' operator, read this: http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex

It would help if your question was more specific. It's hard to answer as asked.

like image 82
S.Lott Avatar answered Sep 19 '22 15:09

S.Lott