So, I have to create a python script that given 2 fractions and an operand will print the result of the operation. This was intended to be solved by firstly asking for one fraction and saving it into a variable, then ask for another fraction and lastly ask for the operand. But out of curiosity I've tried to give this problem a different point of view. My idea was to ask for the full operation and save the input string into a variable, then with the function exec() I could get the decimal result of the given operation, finally to deal with decimals my idea was to multiply by 10 to the power of the number of decimal digits and then dividing by 10 to that same power, this way I could have a fraction as a result. So I went on to code and managed to program this out, my only issue is that the number of decimal digits is limited so normally the result that my script returns is a very big fraction that is very close to what the real fraction is. So I was wondering if there is any workaround for this. Here is my code and an example for further explanation:
op = input('Enter operation: ') try: exec('a = ' + op) except: print('Invalid operation') def euclides(a, b): while a != 0 and b != 0: if a < b: b = b%a else: a = a%b if a == 0: return b elif b == 0: return a print(f'{int(a*10**len(str(a).split(".")[1])/euclides(a*10**len(str(a).split(".")[1]),10**len(str(a).split(".")[1])))}/{int(10**len(str(a).split(".")[1])/euclides(a*10**len(str(a).split(".")[1]),10**len(str(a).split(".")[1])))}') EXAMPLE:
- op input => 4/3+5/7
- Result of script => 5119047619047619/2500000000000000 = 2.04761904761
- Result I'm looking for => 43/21 = 2.047619 period
Thank you for your help in advance
https://stackoverflow.com/questions/66032701/fraction-calculator-in-python-workaround February 04, 2021 at 01:32AM
没有评论:
发表评论