Last active
June 11, 2022 14:31
-
-
Save asukaminato0721/cba84a30bde750e57c7e9b6bc2278ea4 to your computer and use it in GitHub Desktop.
paiza S007: データヒストグラム
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
''' | |
cut token, then use ast to traverse. | |
paiza | |
S007: データヒストグラム | |
''' | |
from collections import defaultdict | |
from dataclasses import dataclass | |
from functools import reduce | |
from operator import mul | |
from string import ascii_lowercase | |
from typing import List, Union | |
S = input() | |
l = len(S) | |
ans = defaultdict(int) | |
@dataclass | |
class Num: | |
val: int | |
level: int = 0 | |
def append(self, value: str): | |
self.val = self.val * 10 + int(value) | |
@dataclass | |
class Alpha: | |
val: str | |
def append(self, value: str): | |
self.val += value | |
@dataclass | |
class Left: | |
... | |
@dataclass | |
class Right: | |
... | |
token: List[Union[Left, Right, Num, Alpha]] = [] | |
for i in range(l): | |
cur = S[i] | |
if cur.isdigit(): | |
if token and isinstance(token[-1], Num): | |
token[-1].append(cur) | |
else: | |
token.append(Num(int(cur))) | |
if cur.isalpha(): | |
token.append(Alpha(cur)) | |
if cur == "(": | |
token.append(Left()) | |
if cur == ")": | |
token.append(Right()) | |
# print(token) | |
stack: List[Num] = [] | |
cur_level = 0 | |
for i in token: | |
if isinstance(i, Left): | |
cur_level += 1 | |
if isinstance(i, Right): | |
cur_level -= 1 | |
stack = [x for x in stack if x.level < cur_level] | |
if isinstance(i, Alpha): | |
for c in i.val: | |
ans[c] += reduce(mul, [x.val for x in stack], 1) | |
stack = [x for x in stack if x.level < cur_level] | |
if isinstance(i, Num): | |
stack.append(Num(i.val, cur_level)) | |
for i in ascii_lowercase: | |
print(i, ans[i]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment