Skip to content

Instantly share code, notes, and snippets.

@tvdsluijs
Created December 28, 2018 19:51
Show Gist options
  • Save tvdsluijs/6dee6287790d4b98a26ee2e80963e588 to your computer and use it in GitHub Desktop.
Save tvdsluijs/6dee6287790d4b98a26ee2e80963e588 to your computer and use it in GitHub Desktop.
Small fractions python calculator
"""
author: Pure Python
url: https://www.purepython.org
copyright: CC BY-NC 4.0
creation date: 28-12-2018
Small script for calculating simple Fractions
Klein script om breuken uit te rekenen.
Calculates fractions like
1/2 * 2/4
or
3/4 - 2/27
or
2/34 / 2/43
or
1/2 + 4/5
"""
import re
import operator
from fractions import Fraction
# setting the operation kinds for the calculation
ops = {'+': operator.add,
'-': operator.sub,
'/': operator.truediv,
':': operator.truediv,
'*': operator.mul}
# the regex to get the fractions and operator from the input
regex = r"([0-9]*\/[0-9*])(\+|\-|\*|\:|\/)([0-9]*\/[0-9*])"
breuk = False
while breuk is False: # keep looping until we have a valid fraction calculation
try:
frac = input("Fraction calculation : ") # function allows user input.
frac = frac.replace(" ",'') # replace space with nothin
m = re.match(regex, frac, flags=0) # search for regex parts
if m.group(1) and m.group(2) and m.group(3): # check if parts are existing
break # when all there, break and continue
except: # when all goes wrong, keep asking!
continue
# do the calculation and print on screen
print(ops[m.group(2)](Fraction(m.group(1)), Fraction(m.group(3))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment