The simplest symbol table: one scope and a set of names.
What to build
A program that checks a program of declarations and uses in a single scope.
Requirements
let NAMEdeclares a name;use NAMEuses one. Check the lines in order.- Print
line K: NAME is not declaredfor a use of a name not declared yet, andline K: NAME is declared twicefor a second declaration. If there are no problems, printok.
Input
Line 1: n. Then n lines, each let NAME or use NAME.
Output
One line per problem, in order, or ok.
Constraints
n ≤ 100.
Example
Input:
4
let x
use x
use y
let y
Output:
line 3: y is not declared
Why it works
A name is visible only from its declaration onwards, so the table must be built and checked in the same pass, in program order.
Examples
Example 1 · Input
4 let x use x use y let y
Expected output
line 3: y is not declared
Example 2 · Input
3 let a use a use a
Expected output
ok
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep a set of declared names, and handle the lines in order.
Hint 2
A use before its declaration is an error, even if the name is declared later.
Solution
Show one correct solution (try it yourself first)
declared = set()
problems = []
for k in range(1, int(input()) + 1):
kind, name = input().split()
if kind == "let":
if name in declared:
problems.append(f"line {k}: {name} is declared twice")
declared.add(name)
elif name not in declared:
problems.append(f"line {k}: {name} is not declared")
print("\n".join(problems) if problems else "ok")