简体   繁体   中英

Syntax for Greatest Common Divisor - Python

The program below was more precise and shorter than mine, and thus more appealing. I understand mod (%), but the rest of the syntax on the line noted is confusing me. Does anyone know what this syntax is called or how it works?

The problem asked to create a function to find the greatest common divisor (gcd) for two integers, which is the largest number that divides both numbers without a remainder.

For example, the gcd of 20 and 12 is 4.

def gcd(x, y):
   while y != 0:
       (x, y) = (y, x % y)    ## What is happening here? What's this syntax called?
   return x 

Link to where I found this program: How to calculate a mod b in python?

Thank you so much for your help!

You have stumbled upon tuple assignments!

In a nutshell, in python, You can assign groups of variables so long as you are assigning them from a structure with the same format

Here is a simpler illustration of what is happening:

a,b = 3,5
#a is now equal to 3 and b is now equal to 5
#You literally could go: 
#   a = 3
#   b = 5
#And it would be logically equivalent 
a+b

Returns

>>>8

In your function, you are assigning the value of y (the second parameter of the function) to the variable x, and updating the value of y to the remainder of x/y.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM