Decide the kind of each lexeme, the core decision of a lexer.
What to build
A program that prints the kind of each space-separated lexeme.
Requirements
- Kinds: KEYWORD (
if,else,while,print,def,return), NUMBER (digits only), NAME (a letter or _ then letters, digits or _), otherwise OP. - Print
KIND lexemefor each, in order.
Input
One line of lexemes separated by spaces.
Output
One line per lexeme.
Constraints
At most 30 lexemes.
Example
Input:
if x > 10 print x
Output:
KEYWORD if
NAME x
OP >
NUMBER 10
KEYWORD print
NAME x
Why it works
Keywords look like names, so the keyword check must come first; that ordering is the same priority rule real lexers use.
Examples
Example 1 · Input
if x > 10 print x
Expected output
KEYWORD if NAME x OP > NUMBER 10 KEYWORD print NAME x
Example 2 · Input
total = total + 1
Expected output
NAME total OP = NAME total OP + NUMBER 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Test in order: keyword (in a set), number (all digits), name (starts with a letter or _), otherwise operator.
Hint 2
str.isdigit() and str.isidentifier() help.
Solution
Show one correct solution (try it yourself first)
KEYWORDS = {"if", "else", "while", "print", "def", "return"}
for lexeme in input().split():
if lexeme in KEYWORDS:
kind = "KEYWORD"
elif lexeme.isdigit():
kind = "NUMBER"
elif lexeme.isidentifier():
kind = "NAME"
else:
kind = "OP"
print(kind, lexeme)