Skip to content

Commit f2b11ed

Browse files
bites 159
1 parent cdce387 commit f2b11ed

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,4 @@
5050
/113/README.md
5151
/119/README.md
5252
/111/README.md
53+
/159/README.md

159/calculator.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import string
2+
3+
4+
def simple_calculator(calculation:str):
5+
"""Receives 'calculation' and returns the calculated result,
6+
7+
Examples - input -> output:
8+
'2 * 3' -> 6
9+
'2 + 6' -> 8
10+
11+
Support +, -, * and /, use "true" division (so 2/3 is .66
12+
rather than 0)
13+
14+
Make sure you convert both numbers to ints.
15+
If bad data is passed in, raise a ValueError.
16+
"""
17+
num1, operator, num2 = calculation.split(" ")
18+
if not num1.lstrip("-").isdigit() and not num2.lstrip("-").isdigit():
19+
raise ValueError
20+
if operator == "+":
21+
return int(num1)+int(num2)
22+
elif operator == "-":
23+
return int(num1)-int(num2)
24+
elif operator == "*":
25+
return int(num1)*int(num2)
26+
elif operator == "/" and num2 == "0":
27+
# return float(num1)/float(num2)
28+
raise ValueError
29+
elif operator == "/" and num2 != "0":
30+
return round(float(num1)/float(num2),ndigits=2)
31+
else:
32+
raise ValueError
33+

159/test_calculator.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import pytest
2+
3+
from calculator import simple_calculator
4+
5+
6+
@pytest.mark.parametrize("arg, expected", [
7+
('2 + 3', 5),
8+
('5 + 11', 16),
9+
('12 + 18', 30),
10+
])
11+
def test_sum(arg, expected):
12+
assert simple_calculator(arg) == expected
13+
14+
15+
@pytest.mark.parametrize("arg, expected", [
16+
('3 - 2', 1),
17+
('16 - 11', 5),
18+
('12 - 18', -6),
19+
])
20+
def test_subtract(arg, expected):
21+
assert simple_calculator(arg) == expected
22+
23+
24+
@pytest.mark.parametrize("arg, expected", [
25+
('2 * 3', 6),
26+
('-5 * -11', 55),
27+
('3 * -6', -18),
28+
])
29+
def test_multiply(arg, expected):
30+
assert simple_calculator(arg) == expected
31+
32+
33+
@pytest.mark.parametrize("arg, expected", [
34+
('2 / 3', 0.67),
35+
('1 / 5', 0.2),
36+
('-2 / 175', -0.01),
37+
])
38+
def test_true_division(arg, expected):
39+
assert round(simple_calculator(arg), 2) == expected
40+
41+
42+
@pytest.mark.parametrize("arg", [
43+
'a / 3', '2 / b', 'c / d', '1 2 3', '1 ^ 2',
44+
'1 x 2', 'some random string', '1 / 0',
45+
'really_bad_data'
46+
])
47+
def test_bad_inputs(arg):
48+
with pytest.raises(ValueError):
49+
simple_calculator(arg)

0 commit comments

Comments
 (0)