找出最大的公约数

5br*_*mzh 1 python python-2.7

def gei(a, b):
     '''
     a, b: only positive integers! If you don't, we will make you. Max 1337
     For extracting the juice of the numbers in the form of a common divider
     '''
     #Not Ruby, no to_i, but int()
     smallest = int(abs(min(a, b)))
     biggest = int(abs(max(a, b)))
     print "You inputed: ", smallest, " and ", biggest, " their order doesn't matter."
     print "Do you want to see guess numbers? Type 'yes', if you do! "
     selection = raw_input()
     print
     print
     #To evade infinite loops and too big numbers, we use count.
     count = 0
     ans = smallest
     truth = str(selection) == str('yes')
     def condition(ans, base):
         ans1 = base % ans == 0
         return ans1
     while condition(ans, biggest) == False or condition(ans, smallest) == False:
         ans -= 1
         count += 1
     if count >= 1337:
         break
     elif truth == True:
         print  ans
     if truth == True:
         print
         print
     print  "After weeks of calculation, here is your greater common divider: "
     return ans
Run Code Online (Sandbox Code Playgroud)

所以,是的,8年级的信息学任务,以提取共同更大的分隔线.我想知道,也许你们知道我怎么能减少它的麻烦?如何避免在里面使用定义并命名这么多变量?

roo*_*oot 8

import fractions
print fractions.gcd(4,8)
>>> 4
Run Code Online (Sandbox Code Playgroud)

但你也可以看一下来源:

def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a
Run Code Online (Sandbox Code Playgroud)

参考:http://en.wikipedia.org/wiki/Euclidean_algorithm