-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemp_converters.py
81 lines (63 loc) · 2.14 KB
/
temp_converters.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from decimal import Decimal, ROUND_HALF_UP
class InvalidTemp(Exception):
pass
class TempConverter(object):
@staticmethod
def f_to_c(temp_f):
return (temp_f - 32) * 5/Decimal('9.0')
@staticmethod
def f_to_k(temp_f):
return (temp_f + Decimal('459.67')) * 5/Decimal('9.0')
@staticmethod
def f_to_r(temp_f):
return temp_f + Decimal('459.67')
@staticmethod
def c_to_f(temp_c):
return (temp_c * 9/Decimal('5.0')) + 32
@staticmethod
def c_to_k(temp_c):
return temp_c + Decimal('273.15')
@staticmethod
def c_to_r(temp_c):
return (temp_c * 9/Decimal('5.0')) + Decimal('491.67')
@staticmethod
def k_to_c(temp_k):
if temp_k < 0:
raise InvalidTemp("Invalid Temp")
return temp_k - Decimal('273.15')
@staticmethod
def k_to_f(temp_k):
if temp_k < 0:
raise InvalidTemp("Invalid Temp")
return (temp_k * 9/Decimal('5.0')) - Decimal('459.67')
@staticmethod
def k_to_r(temp_k):
if temp_k < 0:
raise InvalidTemp("Invalid Temp")
return temp_k * 9/Decimal('5.0')
@staticmethod
def r_to_c(temp_r):
if temp_r < 0:
raise InvalidTemp("Invalid Temp")
return (temp_r - Decimal('491.67')) * 5/Decimal('9.0')
@staticmethod
def r_to_f(temp_r):
if temp_r < 0:
raise InvalidTemp("Invalid Temp")
return temp_r - Decimal('459.67')
@staticmethod
def r_to_k(temp_r):
if temp_r < 0:
raise InvalidTemp("Invalid Temp")
return temp_r * 5/Decimal('9.0')
def run_conversion(self, orig_temp, orig_scale, dest_scale, student_answer):
conversion = "{0}_to_{1}".format(orig_scale[0].lower(), dest_scale[0].lower())
try:
answer = getattr(self, conversion)(Decimal(orig_temp))
if answer.quantize(0, rounding=ROUND_HALF_UP) == Decimal(student_answer).quantize(0, rounding=ROUND_HALF_UP):
result = "correct"
else:
result = "incorrect"
except InvalidTemp as exc:
result = "invalid"
return result