Nested Store Class
Python
Hard
2 views
Problem Description
You will receive q commands: SET path value, GET path. Path is dot separated. Create Store class to handle. For GET output value or NOT FOUND.
Input Format
First line q. Next q lines commands.
Output Format
Outputs for GET.
Sample Test Case
Input:
6
SET user.name Ravi
SET user.age 20
GET user.name
GET user.city
SET user.city Delhi
GET user.city
Output:
Ravi
NOT FOUND
Delhi
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
class Store:
def __init__(self):
self.root={}
def setv(self,path,val):
keys=path.split('.')
cur=self.root
for k in keys[:-1]:
nxt=cur.get(k)
if not isinstance(nxt,dict):
nxt={}
cur[k]=nxt
cur=nxt
cur[keys[-1]]=val
def getv(self,path):
keys=path.split('.')
cur=self.root
for k in keys:
if isinstance(cur,dict) and k in cur:
cur=cur[k]
else:
return None
return cur if not isinstance(cur,dict) else None
st=Store()
out=[]
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
if parts[0]=='SET':
st.setv(parts[1], parts[2] if len(parts)>2 else '')
else:
v=st.getv(parts[1])
out.append(str(v) if v is not None else 'NOT FOUND')
print('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!