本帖最后由 TJBEST 于 2020-3-5 10:41 编辑
我觉得平时的练习还使用库就起不到锻炼的价值,所以我还是自己编def fun343(numArr):
def splitNum(numArr):
result = []
temp = numArr[0]
couple = []
for each in numArr[1:]:
if each == '/':
couple.append(int(temp))
temp = ''
elif each == '+' or each == '-':
couple.append(int(temp))
result.append(tuple(couple))
temp = each
couple.clear()
else:
temp += each
couple.append(int(temp))
result.append(tuple(couple))
return result
def Jiyue(p,q):
Max = max([abs(p),q])
Min = min([abs(p),q])
if Min == 0:
return (0,1)
while True:
res = Max % Min
if res == 0:
yueshu = Min
break
else:
Max = Min
Min = res
return (p//yueshu,q//yueshu)
def add(fen1,fen2):
Mu = fen1[1] * fen2[1]
Zi = fen1[0] * fen2[1] + fen1[1] * fen2[0]
if Mu * Zi > 1e20:#减小运算量 步步约分耗时间
return Jiyue(Zi,Mu)
else:
return (Zi,Mu)
numList = splitNum(numArr)
preNum = (0,1)
for eachNum in numList:
preNum = add(preNum,eachNum)
preNum = Jiyue(preNum[0],preNum[1])
return '{0:d}/{1:d}'.format(preNum[0],preNum[1])
|