两个算分数(比例)的小程序 [Python]

随手写的小程序 很小很实用, 尤其是在压片的时候计算sar值等方面.
第一个: 化简分数

样例输入1: 16/12
样例输出1: 4 : 3

样例输入2: 16*480/(9*704)
样例输出2: 40 : 33

恩, 简单说来, 就是化任意分数为最简分数
第二个: 小数化分数
给一个范围,用范围内的数组成分数,并使这个分数的值最接近所给的小数(如样例给的是1-100和1-1000的范围)

样例输入1: 3.1415926535897 100
样例输出1: 22 : 7

样例输入2: 3.1415926535897 1000
样例输出2: 355 : 113
以下是全部代码:
第一个:

def gcd(m, n):
    while n:
        m, n = n, m % n
    return m
import sys
if len(sys.argv)<2:
    print "Enter the (num/num):",
    m = raw_input()
else:
    m = sys.argv[1]
k = m.split('/')
if len(k)<2:
    print "Input error!"
    sys.exit()
a1=eval(k[0])
a2=eval(k[1])
a3 = gcd(a1,a2)
print a1/a3,":",a2/a3

第二个:

def gcd(m, n):
    while n:
        m, n = n, m % n
    return m
import sys
if len(sys.argv)<2:
    print "Enter the num and up:",
    m = raw_input()
else:
    m = " ".join(sys.argv[1:])
m=m.split()
if len(m)<2:
    print "Input error!"
    sys.exit()
b=int(m[1])
t=eval(m[0])
a1=1
a2=1
mina1=1
mina2=1
mindt=10000
while a1<b+1 and a2<b+1:
    a3=a1*1.0/a2
    if abs(a3-t)<mindt:
        mindt=abs(a3-t)
        mina1=a1
        mina2=a2
    if a3<t:
        a1+=1
    elif a3>t:
        a2+=1
    else:
        break
a3 = gcd(mina1,mina2)
print mina1/a3,":",mina2/a3
This entry posted in Python 代码. Entry Tags: , Bookmark the permalink. 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>