[Kattis] Adding Words
Here you will find the step by step walkthrough and solution for the programming puzzle “adding words” from Kattis. You can find the video which describes the solution step by step here:
And here is the code for the solution:
# Econowmics.com
# Youtube.com/@codedabacus
# storage for the mappings
words = {}
# functions
def find_key(value):
values = {v: k for k,v in words.items()}
return values[value] if value in values else "unknown"
def calculation(command):
tmp = []
for x in command[:-1]:
# operand
if x in ['+', '-']:
tmp.append(x)
# variable
elif x in words:
tmp.append(words[x])
else:
return " ".join(command) + " unknown"
ans = str(eval(' '.join(tmp)))
res = find_key(ans)
return " ".join(command) + " " + res
# input ends at the end of the file
while True:
try:
command = input().split()
# Definition
if command[0] == 'def':
words[command[1]] = command[2]
# Calculation
elif command[0] == 'calc':
# 'calc'
c = command[1:]
print(calculation(c))
except EOFError:
break