Exercise: gcd recur

The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder.

gcd(6, 12) = 6

A clever mathematical trick (due to Euclid) makes it easy to find greatest common divisors. Suppose thataandbare two positive integers:

  • If b = 0, then the answer is a

  • Otherwise, gcd(a, b) is the same as gcd(b, a % b)

function gcd(a, b)
    if b = 0
       return a; 
    else
       return gcd(b, a mod b);

Exercise: is in

Use the idea of bisection search to determine if a character is in a string, so long as the string is sorted in alphabetical order.

问题 :python3中testchar = aStr[int(len(aStr)/2)] 里面如果没有int,则输出不是integer。Python2则可以。

def isIn(char, aStr):  
    testchar = " " 
    while testchar != char: 
        if len(aStr)==0 or len(aStr)==1 : 
            if char == aStr: 
                return True 
            else: 
                return False 
        elif len(aStr)>1 and len(aStr)%2 == 0: 
            testchar = aStr[int(len(aStr)/2)]
            print (int(len(aStr)/2)) 
            print (testchar)
            if testchar == char: 
                return True 
            elif testchar < char: 
                return isIn(char, aStr[int(len(aStr)/2+1):]) 
            else: 
                return isIn(char, aStr[0:int(len(aStr)/2)]) 
        elif len(aStr)>1 and len(aStr)%2 == 1: 
            testchar = aStr[int((len(aStr)-1)/2)]
            print (int((len(aStr)-1)/2))
            print (testchar)
            if testchar == char: 
                return True 
            elif testchar < char: 
                return isIn(char, aStr[int((len(aStr)-1)/2+1):]) 
            else: 
                return isIn(char, aStr[0:int((len(aStr)-1)/2)])

print(isIn("t","adefhikllnnnottuxyz"))

results matching ""

    No results matching ""