小数转分数

好久没写过算法方面的代码了,偶然翻开《编程之美》看到了这个题,拿来写写。具体算法在《编程之美》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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值