Problem 147520 · hard · Phase 01 Prerequisites & Setup

The Carpenter's Fraction Calculator

strings · functions · arithmetic · integer division · modulo

A carpenter types calculations such as 3 1/4 + 2 5/8 and wants the answer as a mixed number in lowest terms. Write fraction_calc(expr) that returns the answer as a string.

expr is left op right: one operator from + - * / with one space on each side. Each operand is one of:

  • a whole number: 7, -5, 0
  • a fraction: 3/4, -9/4 (may be improper or not in lowest terms)
  • a mixed number: 2 1/3, -2 1/3 (whole part, one space, a fraction with 0 <= numerator; a leading - makes the whole mixed number negative, so -2 1/3 is -7/3)

The answer is written the same way: 0, 5, -5, 3/4, -3/4, 2 1/3, -2 1/3, with the fraction part in lowest terms and smaller than 1. Dividing by zero returns "undefined".

Examples

Input:  expr = "3 1/4 + 2 5/8"
Output: "5 7/8"

Input:  expr = "1/2 - 2 3/4"
Output: "-2 1/4"

Input:  expr = "-1 1/2 * -4/6"
Output: "1"

Constraints

  • whole numbers and numerators are between 0 and 10**6 in size; denominators are between 1 and 1000

Goals

  • Parse mixed numbers such as -2 1/3 into a numerator and denominator
  • Add, subtract, multiply and divide fractions exactly with integers
  • Print a result in lowest terms as a mixed number with the sign in the right place
Starting Python…