用python带分数和分数
发布网友
发布时间:2022-05-10 23:46
我来回答
共2个回答
热心网友
时间:2022-05-11 01:15
#!/usr/bin/env python3
from random import randint, choice
def mm(m, n):
"""求两个整数的最小公倍数"""
if m > n:
m, n = n, m
if m == n or m == 1 or n % m == 0:
return n
for i in range(2, n+1):
if m * i % n == 0:
return m * i
def mn(m, n):
"""求两个整数的最小公约数"""
if m > n:
m, n = n, m
if m == n or m == 1 or n % m == 0:
return m
r = 1
for i in range(2, m):
if m % i == 0 and n % i == 0:
r = i
return r
def rd(t=3):
"""随机生成一个分数"""
w = randint(1, 9)
d = randint(2, 9)
n = randint(1, d-1)
m = mn(d, n)
return [w, n//m, d//m]
def show(a):
"""[1, 1, 2] --> '1 1/2'"""
return '{} {}/{}'.format(*a)
def imp(a):
"""1 1/2 --> 3/2"""
return [a[0]*a[2]+(a[0]//abs(a[0]))*a[1], a[2]]
def unimp(a):
"""3/2 --> 1 1/2"""
m = mn(abs(a[0]), a[1])
n, d = a[0] // m, a[1] // m
return (n//abs(n))*(abs(n) // d), abs(n) % d, d
def add(a, b, negative=False):
a, b = imp(a), imp(b)
m = mm(a[1], b[1])
sign = -1 if negative else 1
r = a[0] * m // a[1] + sign * b[0] * m // b[1], m
return unimp(r)
def main():
right = 0
for i in range(20):
print('Question {}:'.format(i+1))
a, s, b = rd(), choice(('+', '-')), rd()
result = show(add(a, b, s=='-'))
inp = input('{} {} {} = '.format(show(a), s, show(b))).strip()
if inp == result or inp == result.lstrip('0 '):
right += 1
print('Right.')
else:
print('Wrong!The correct result is: {}'.format(result.lstrip('0 ')))
print('Test complete. Right: {}, wrong: {}, Rate: {}%'.format(
right, 20-right, right*5))
if __name__ == '__main__':
main()