Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1#!/usr/bin/env python3 

2 

3"""Solution to chapter 6, exercise 26: calc""" 

4 

5import operator 

6 

7 

8def calc(to_solve): 

9 """This function expects to get a string containing a 

10two-argument math expression in prefix notation, and with 

11whitespace separating the operator and numbers. 

12The return value is the result from invoking this function. 

13""" 

14 

15 operations = {'+': operator.add, 

16 '-': operator.sub, 

17 '*': operator.mul, 

18 '/': operator.truediv, 

19 '**': operator.pow, 

20 '%': operator.mod} 

21 

22 op, first_s, second_s = to_solve.split() 

23 first = int(first_s) 

24 second = int(second_s) 

25 

26 return operations[op](first, second)