Startup | Onsite Interview | Variation of Basic Calculator
Anonymous User
324

Given a list of strings containing expressions, assignments and eval statements, print or return the correct answer whenever an eval is encountered.
There can be multiple expressions for the same value, in that case print the last correct value or None if there is no value at that point

Ex:
input = ['A=B+C', 'B=D+E', 'C=10', 'D=5', 'E=2', 'eval A']
output = 17

There can be multple evals:
input = ['A=B+C', 'B=D+E', 'eval A', 'C=10', 'D=5', 'E=2', 'eval A']
output = None, 17

Get the last correct value:
input = ['A=B+C', 'B=D+E', 'C=10', 'D=5', 'E=2', 'eval A', 'G=7', 'A=D+G', 'eval A']
output = 12 (lastest eval statement overrides previous eval A)

Implement this and extend it to all operations -, *, /.

My take on this:
Created two dictionaries, one to store list of expressions {'A' : ['B+C', 'D+G'], 'B':['D+E'] and so on}
one to store values {'C' : 10, 'D' : 5}
And one array to store evals : [A]

Loop over the eval array, look it up in expressions, recursively find all expression and values.

Couldn't finish it in time, any better way to approach this?

Comments (2)