小数转分数

好久没写过算法方面的代码了,偶然翻开《编程之美》看到了这个题,拿来写写。具体算法在《编程之美》2.6和2.7。
#! /usr/bin/python

def is_even(x):
    if 0 == (x & 1):
        return True
    else:
        return False

def cal_gcd(x, y):
    if x < y:
        return cal_gcd(y, x)
    if 0 == y:
        return x
    if is_even(x):
        if is_even(y):
            return (cal_gcd(x >> 1, y >> 1) << 1)
        else:
            return cal_gcd(x >> 1, y)
    else:
        if is_even(y):
            return cal_gcd(x, y >> 1)
        else:
            return cal_gcd(x - y, y)

def decimal_to_fraction(x):
    i, temp = str(x).split('.')
    i = long(i)
    num = 0
    den = 0
    pos = temp.find('(')
    if -1 != pos:
        a = 0
        if pos > 0:
            a = long(temp[0:pos])
        b = long(temp[pos + 1:-1])
        if 0 != b:
            num = a * (10 ** (len(temp) - pos - 2) - 1) + b
            den = (10 ** (len(temp) - pos - 2) - 1) * (10 ** pos)
        else:
            num = a
            den = 10 ** pos
    else:
        num = long(temp)
        den = 10 ** len(temp)
    num += (i * den)
    g = cal_gcd(num, den)
    return str(num / g) +  ' / ' + str(den / g)

if __name__ == '__main__':
    try:
        dec = str(raw_input())
        ans = decimal_to_fraction(dec)
        print(ans)
    except Exception, e:
        print('exception: ', e)

你可能感兴趣的:(python,小数,分数)