-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask_C.py
More file actions
118 lines (108 loc) · 2.56 KB
/
Task_C.py
File metadata and controls
118 lines (108 loc) · 2.56 KB
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
operators = ['+', '-', '*', '/', '<', '=', '>', '?']
def get_n_arg(operator):
if operators.count(operator) == 0:
return(0)
if operators.index(operator) < 7:
return(2)
else:
return(3)
def is_operator(element):
return(operators.count(element) > 0)
def is_variable(element):
return(element.isalpha())
def get_vars(elements):
formula_vars = []
for element in elements:
if not is_operator(element):
if is_variable(element):
if formula_vars.count(element) == 0:
formula_vars.append(element)
try:
formula_vars.sort()
except:
return(formula_vars)
return(formula_vars)
def calc_formula(elements, value_set, var_to_val):
try:
if len(elements) == 1:
return(value_set[0])
operator = elements.pop()
if not is_operator(operator):
return(0)
operands = []
except:
return(0)
for i in range(get_n_arg(operator)):
try:
element = elements.pop()
except:
return(0)
if is_operator(element):
elements.append(element)
operands.append(calc_formula(elements, value_set, var_to_val))
elif is_variable(element):
try:
if var_to_val.index(element) >= len(value_set):
operands.append(0)
else:
operands.append(int(value_set[var_to_val.index(element)]))
except:
return(0)
else:
try:
tmp = int(element)
except:
return(0)
operands.append(tmp)
try:
if len(operands) < 2:
return(0)
if operator == '+':
return(operands[1] + operands[0])
if operator == '-':
return(operands[1] - operands[0])
if operator == '*':
return(operands[1] * operands[0])
if operator == '/':
if operands[0] == 0:
return(0)
return(operands[1] // operands[0])
if operator == '<':
return(operands[1] < operands[0])
if operator == '=':
return(operands[1] == operands[0])
if operator == '>':
return(operands[1] > operands[0])
if operator == '?':
if len(operands) < 3:
return(0)
if operands[2]:
return(operands[1])
else:
return(operands[0])
except:
return(0)
return(0)
def calc(d):
try:
K = int(d[0])
Formula_elements = d[1].split(' ')
N = int(d[2])
Value_set = d[3].split(' ')
var_to_val = get_vars(Formula_elements)
return(calc_formula(Formula_elements, Value_set, var_to_val))
except:
return(0)
if __name__ == '__main__':
K = input()
Formula = input()
N = input()
Value_sets = []
try:
Num = int(N)
except:
Num = 1
for i in range(Num):
Value_sets.append(input())
for value_set in Value_sets:
print(calc([K, Formula, N, value_set]))