开发者

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

开发者 https://www.devze.com 2023-03-31 17:31 出处:网络
I found this greatest common denominator code: def gcd(x,y): while y: x, y = y, x % y retu开发者_Python百科rn x

I found this greatest common denominator code:

def gcd(x,y):
    while y:
        x, y = y, x % y
    retu开发者_Python百科rn 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?


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.


  1. The loop ceases when y==0.

  2. The loop body simultaneously assigns y to x and x%y to y. Otherwise, you would need a temporary variable to execute both assignments, because one of them would be overwritten.


The expression while y will iterate so long as y is not zero.

The other line is performing the two operations atomically:

new_x <-- old_x
new_y <-- old_x mod old_y

This performs euclidean algorithm for GCD, and the tuple assignment obviates the need for a temporary variable.


Greatest Common Divisor using the Euclidean algorithm

while y != 0:
    temp = y
    y = x % y
    x = temp
return x
0

精彩评论

暂无评论...
验证码 换一张
取 消