Understanding the implementation of the Euclidean algorithm for GCF in Python

Euclid's algorithm for GCF two numbers GCF(a, b)=GCF(b, a mod b). I saw this implemented in Python as follows:

def gcf(a, b):
    return b and gcf(b, a%b) or a

I don’t understand how to parse this function or specifically how logical logic is applied to integers. Eg gcf(42, 56) = 14. When I go through it, I see that ultimately the recursive part returns zero. I follow 0 or n == nand 0 and n == 0. However, when I compare a pair of nonzero numbers with logic and / or logic, I do not understand what is happening and why.

Can anyone get through this feature?

+3
source share
4 answers

Python 'and' ' . , .

0 n - n

0 n - 0

a and b or c - (a ? b : c) C.

4.6 Python python .

+2

:

gcf (42, 56)
gcf (56, 42)//, b , 42% 56 (= 42) gcf (42, 14)// b , 56% 42 (= 14) gcf (14, 0)//, b , 42% 14 (= 0) return a//, b , (14)

. python, , , popping , 1/true.

+1

, / , , .

, , , .

x or yx, if x: , y.

x and yx, if x: , y.

, GvR . , , , , , , x if C else y ​​ .

, ... . REPL :)

+1

b , gcf (b, a% b) (recurse). b , .

0

Source: https://habr.com/ru/post/1781076/


All Articles