Last active
April 16, 2024 03:36
-
-
Save asukaminato0721/d7ee47a4d7ed314d6d1397e949e8b131 to your computer and use it in GitHub Desktop.
simple-parser-v1.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# only consider base case | |
from enum import Enum, auto | |
import re | |
from typing import List, Union | |
class Status(Enum): | |
Normol = auto() | |
Number = auto() | |
class Type(Enum): | |
digit = auto() | |
operator = auto() | |
space = auto() | |
unkonwn = auto() | |
s = """111 + 2 - 5 / 6 + 888""" | |
def str2type(s: str): | |
if re.match("[0-9]", s): | |
return Type.digit | |
if re.match(r"[\+\-\*\/]", s): | |
return Type.operator | |
if s.isspace(): | |
return Type.space | |
return Type.unkonwn | |
index = 0 | |
arr: List[Union[str, int]] = [] | |
status = Status.Normol | |
cur = "" | |
while index < len(s): | |
fast = s[index] | |
match (status, str2type(fast)): | |
case (Status.Normol, Type.digit): | |
cur += fast | |
status = Status.Number | |
case (Status.Normol, Type.operator): | |
arr.append(fast) | |
case (Status.Normol, Type.space): | |
# ignore | |
... | |
case (Status.Number, Type.digit): | |
cur += fast | |
case (Status.Number, Type.operator): | |
arr.append(int(cur)) | |
cur = "" | |
arr.append(fast) | |
status = Status.Normol | |
case (Status.Number, Type.space): | |
arr.append(int(cur)) | |
cur = "" | |
status = Status.Normol | |
case (_, Type.unkonwn): | |
... | |
index += 1 | |
arr.append(int(cur)) | |
print(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment