Evaluate Simple Expression
Python
Medium
2 views
Problem Description
Read n assignments like name value (integer). Then one expression is provided as: name1 op name2 where op is + or -. Output result using stored values. Missing names are treated as 0.
Input Format
First line n. Next n lines: name value. Last line: name1 op name2.
Output Format
One integer result.
Sample Test Case
Input:
3
a 10
b 4
c 2
a - b
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
mp={}
for i in range(1,1+n):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
mp[parts[0]]=int(parts[1])
expr=(lines[1+n] if 1+n<len(lines) else '').split()
if len(expr)<3:
sys.exit(0)
x=mp.get(expr[0],0)
op=expr[1]
y=mp.get(expr[2],0)
ans=x+y if op=='+' else x-y
sys.stdout.write(str(ans))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!