#!/usr/bin/env python3 # Assumptions: # - Input has proper syntax # - Only performs ops: minus, plus, times, divided by # - Numbers are integers import re from operator import mul, truediv, sub, add instr = input() #"7 times 2 plus 22 minus 5 plus 6 times 2 divided by 3" numbers = [int(x) for x in re.split('minus|plus|times|divided by', instr)] operations = re.findall('(minus|plus|times|divided by)', instr) i = 0 def do_op(op): global i numbers[i] = op(numbers[i], numbers[i+1]) del operations[i] del numbers[i+1] i = i - 1 while i < len(operations): op = operations[i] if op == "times": do_op(mul) if op == "divided by": do_op(truediv) i = i + 1 i = 0 while i < len(operations): op = operations[i] if op == "minus": do_op(sub) if op == "plus": do_op(add) i = i + 1 print(numbers[0])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question