【Python】PAT-1034 有理数四则运算
生活随笔
收集整理的這篇文章主要介紹了
【Python】PAT-1034 有理数四则运算
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
2. 代碼
2.1 分析
題目本身不難。但是我前前后后花了2h以上。
題目需要處理的判斷邏輯還是比較多的。
我通過實現一個Fraction的類來完成了題目。
關于最后一個測試點,非常有可能是類似這樣的結構 。
1/2 -1/2, 這兩個分數相除,分母會出現負數,所以一定要處理妥當。
否則最后一個測試點過不了。
2.2 代碼
class Fraction():# 默認分母=1,且是正數(flag=""正數,flag="-"負數)def __init__(self, top, bottom=1):is_positive = 1if top*bottom < 0:is_positive = -1# 全都轉化成正數top, bottom = abs(top), abs(bottom)# 分子分母化簡max_factor = gcd(top, bottom)if bottom != 0:# 約分self.num = is_positive * (top//max_factor)self.den = bottom // max_factorelse:# 分母為0,分式沒有意義self.num = 0self.den = 0# 顯示數據def show(self):num, den = self.num, self.den# 判斷是否是正數is_positive = 1if num*den < 0:is_positive = -1# 全部轉化成正數num, den = abs(num), abs(den)# 分母為0if den == 0:return "Inf"# 分子為0if num == 0:return 0# 分母為1if den == 1:if is_positive == 1:return "%d" % (num)else:return "(-%d)" % (num)# 最簡化有理數int_num = num // dennum = num % denif int_num == 0:# 正負判定if is_positive != 1:return "(-%d/%d)" % (num, den)else:return "%d/%d" % (num, den)else:# 正負判定if is_positive != 1:return "(-%d %d/%d)" % (int_num, num, den)else:return "%d %d/%d" % (int_num, num, den)# 加法def __add__(self, other):# 通分x = self.num*other.den + self.den*other.numy = self.den * other.denmax_factor = gcd(abs(x), y)return Fraction(x//max_factor, y//max_factor)# 減法def __sub__(self, other):x = self.num*other.den - self.den*other.numy = self.den * other.denmax_factor = gcd(abs(x), y)return Fraction(x//max_factor, y//max_factor)# 乘法def __mul__(self, other):x = self.num * other.numy = self.den * other.denmax_factor = gcd(abs(x), y)return Fraction(x//max_factor, y//max_factor)# 對應除法( / )def __truediv__(self, other):x = self.num * other.deny = self.den * other.num# 分母為0,沒有意義,直接返回if y == 0:return Fraction(0, 0)max_factor = gcd(abs(x), abs(y))# 分子、分母 有一個是負數if (x < 0 and y >= 0) or (x >= 0 and y < 0):return Fraction(-(abs(x)//max_factor), abs(y)//max_factor)else:return Fraction(x//max_factor, y//max_factor)def gcd(x, y):# x,y 必須都是自然數if x < y:x, y = y, xwhile(y != 0):temp = xx = yy = temp % yreturn xx, y = input().split(" ") a1, b1 = tuple(map(int, x.split("/"))) a2, b2 = tuple(map(int, y.split("/")))x = Fraction(a1, b1) y = Fraction(a2, b2)print(x.show(), "+", y.show(), "=", (x+y).show()) print(x.show(), "-", y.show(), "=", (x-y).show()) print(x.show(), "*", y.show(), "=", (x*y).show()) print(x.show(), "/", y.show(), "=", (x/y).show())3. AC截圖
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的【Python】PAT-1034 有理数四则运算的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【5分钟搞定】如何将py打包成exe可执
- 下一篇: 【IDEA】干掉注释自动在行首