-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
119 lines (108 loc) · 2.85 KB
/
functions.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import arith
'''
Contains the implemented functions and their names. This dictionary
is referenced when checking whether or not a command entered is a valid
function. The dictionary contains of key: value pairs, where key is a string
containing the function name and value is a reference to the function that
was implemented.
In case a new function is added to the calculator, make sure to update this
dictionary.
'''
function_table = {
'sub': arith.sub,
'sum': arith.sum,
'divide': arith.divide,
'multiply': arith.multiply,
'power': arith.power,
'sqrt': arith.sqrt,
'mod': arith.mod,
'gcd': arith.gcd,
'lcm': arith.lcm,
'bin': arith.bin
}
arity_table = {
'sub': 2,
'sum': 2,
'divide': 2,
'multiply': 2,
'power': 2,
'sqrt': 1,
'mod': 2,
'gcd': 2,
'lcm': 2,
'bin': 1
}
types_table = {
'sub': int,
'sum': int,
'divide': int,
'multiply': int,
'power': int,
'sqrt': int,
'mod': int,
'gcd': int,
'lcm': int,
'bin': str
}
'''
Returns True if function_name provided is a valid function, else False.
'''
def is_function(function_name):
return function_name in function_table
'''
Returns the function according to function_name.
'''
def get_function(function_name):
return function_table[function_name]
'''
Returns the arity of the function according to function_name.
'''
def get_arity(function_name):
return arity_table[function_name]
'''
Returns the type of _all_ parameters of the function according to function_name.
'''
def get_type(function_name):
return types_table[function_name]
'''
Prints the available functions and their arity.
'''
def print_functions():
print('supported functions:')
for function_name in function_table.keys():
print('"%s" arity: %i' % (function_name, arity_table[function_name]))
'''
Processes the given input
'''
def process_line(expression):
# Tokenize string
expression = expression.split()
operands = []
for x in expression:
# Is the token a function name?
if is_function(x):
# Retrieve function
function_name = x
# Is the token an operand?
elif x.isnumeric():
# Correct type
try:
# Store operand
operands.append(get_type(function_name)(x))
# Wrong type
except:
# Output: 'invalid operand type'
print('invalid operand type')
# Otherwise
else:
# Output: unknown token'
print('unknown token')
return
# Correct arity?
if get_arity(function_name) == len(operands):
# Call function and output result
print(get_function(function_name)(*operands))
# Otherwise
else:
# Output: 'Invalid number of operands'
print('invalid number of operands')