Apply the longest-match rule by hand.
What to build
A program that splits a line of operators into tokens using longest match.
Requirements
- Two-character operators:
==,!=,<=,>=,+=,-=,->. One-character operators:= ! < > + -. - Print the tokens separated by single spaces. On any other character print
error at C(C counted from 1) instead.
Input
One line of operators and spaces.
Output
One line.
Constraints
At most 80 characters.
Example
Input:
<=>=
Output:
<= >=
Why it works
Trying the longer operator first at every position is the longest-match rule, which gives the tokens a programmer intends.
Examples
Example 1 · Input
<=>=
Expected output
<= >=
Example 2 · Input
===
Expected output
== =
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
At each position, check whether two characters form an operator before trying one.
Hint 2
Skip spaces; anything that is not an operator is an error.
Solution
Show one correct solution (try it yourself first)
TWO = {"==", "!=", "<=", ">=", "+=", "-=", "->"}
ONE = set("=!<>+-")
text = input()
tokens = []
i = 0
error = None
while i < len(text):
if text[i] == " ":
i += 1
elif text[i:i + 2] in TWO:
tokens.append(text[i:i + 2])
i += 2
elif text[i] in ONE:
tokens.append(text[i])
i += 1
else:
error = i + 1
break
print(f"error at {error}" if error else " ".join(tokens))