Dependency Assignments
Python
Hard
2 views
Problem Description
You will receive n assignments like x = y + 5 or x = 10. Variables are single lowercase letters. Compute final values for all variables that appear on left side, assuming missing variables start at 0. Output values for a..z that were assigned at least once.
Input Format
First line n. Next n lines assignments.
Output Format
Multiple lines: var value.
Sample Test Case
Input:
4
x = 10
y = x + 5
x = y + 1
z = a + 2
Official Solution
import sys,re
lines=sys.stdin.read().splitlines()
if not lines or not lines[0].strip():
sys.exit(0)
n=int(lines[0].strip())
vals={}
assigned=set()
pat=re.compile(r'^([a-z])\\s*=\\s*(?:(-?\\d+)|([a-z])\\s*\\+\\s*(-?\\d+))\\s*$')
for i in range(1,1+n):
line=(lines[i] if i<len(lines) else '').strip()
m=pat.match(line)
if not m:
continue
x=m.group(1)
if m.group(2) is not None:
vals[x]=int(m.group(2))
else:
y=m.group(3)
k=int(m.group(4))
vals[x]=vals.get(y,0)+k
assigned.add(x)
out=[]
for ch in sorted(assigned):
out.append(f'{ch} {vals.get(ch,0)}')
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!