-
Notifications
You must be signed in to change notification settings - Fork 0
/
7 kyu Make a function that does arithmetic!.py
64 lines (41 loc) · 1.48 KB
/
7 kyu Make a function that does arithmetic!.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
https://www.codewars.com/kata/583f158ea20cfcbeb400000a/train/python
Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them.
a and b will both be positive integers, and a will always be the first number in the operation, and b always the second.
The four operators are "add", "subtract", "divide", "multiply".
A few examples:
arithmetic(5, 2, "add") => returns 7
arithmetic(5, 2, "subtract") => returns 3
arithmetic(5, 2, "multiply") => returns 10
arithmetic(5, 2, "divide") => returns 2.5
ArithmeticFunction.arithmetic(5, 2, "add") => returns 7
ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3
ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10
ArithmeticFunction.arithmetic(5, 2, "divide") => returns 2
Try to do it without using if statements!
"""
def arithmetic(a, b, operator):
def add():
return a + b
def subtract():
return a - b
def multiply():
return a * b
def divide():
return a / b
method = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide
}
return method[operator]()
# very proud of myself, coz no 'if-else'
# more compact:
# def arithmetic(a, b, operator):
# return {
# 'add': a + b,
# 'subtract': a - b,
# 'multiply': a * b,
# 'divide': a / b,
# }[operator]