forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
addingwords.py
64 lines (52 loc) · 1.54 KB
/
addingwords.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
import fileinput
words = {}
other = {}
for line in fileinput.input():
line = line.split()
# Clear out all of the word definitions
if line[0] == "clear":
words = {}
other = {}
# Set insert the word into both dictionaries
if line[0] == "def":
# Get new var names
word = line[1]
value = int(line[2])
# Remove any existing old definitions
if word in words:
oldvalue = words[word]
other.pop(oldvalue, None)
# Add new definitions
words[word] = value
other[value] = word
# Calculate the value of a string
if line[0] == "calc":
# Split into words and operators
line = line[1:]
var = line[::2]
ops = line[1::2]
# Keep track of whether answer is unknown
unknown = False
# Check all vars exist
for variable in var:
if variable not in words:
unknown = True
# Calculate total if they do
if not unknown:
# Calculate total
total = words[var[0]]
for i in range(len(ops)-1):
if ops[i] == '+':
total += words[var[i+1]]
if ops[i] == '-':
total -= words[var[i+1]]
# Check answer exists
if total not in other:
unknown = True
# Print answer
for i in line:
print(i, end=' ')
if unknown:
print('unknown')
else:
print(other[total])