Created
December 6, 2025 18:54
-
-
Save mypy-play/af17347fec68668c12dba2de4175670a to your computer and use it in GitHub Desktop.
Shared via mypy Playground
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
| from ib111 import week_11 # noqa | |
| # † V tomto příkladu budeme pracovat s n-árními stromy, které nemají | |
| # v uzlech žádné hodnoty (mají pouze stromovou strukturu). | |
| # Třídu Tree nijak nemodifikujte. | |
| class Tree: | |
| def __init__(self) -> None: | |
| self.children: list[Tree] = [] | |
| # Napište (čistou) funkci, které na základě dobře uzávorkovaného | |
| # řetězce tvořeného pouze znaky ‹(› a ‹)› vybuduje instanci výše | |
| # popsaného stromu, a to tak, že každý pár závorek reprezentuje | |
| # jeden uzel, a jejich obsah reprezentuje podstrom, který v tomto | |
| # uzlu začíná. Ve vstupním řetězci bude vždy alespoň jeden pár | |
| # závorek. | |
| def build_tree(brackets: str) -> Tree: | |
| result, _ = rec_tree(0, brackets) | |
| return result | |
| def rec_tree(position: int, brackets: str) -> tuple[Tree, int]: | |
| position += 1 | |
| node = Tree() | |
| while brackets[position] != ")": | |
| child, position = rec_tree(position, brackets) | |
| node.children.append(child) | |
| position += 1 | |
| return node, position | |
| def main() -> None: | |
| t2 = build_tree("()") | |
| assert len(t2.children) == 0 | |
| t3 = build_tree("(()(()())(()))") | |
| assert len(t3.children) == 3 | |
| assert len(t3.children[0].children) == 0 | |
| assert len(t3.children[1].children) == 2 | |
| assert len(t3.children[1].children[0].children) == 0 | |
| assert len(t3.children[1].children[1].children) == 0 | |
| assert len(t3.children[2].children) == 1 | |
| assert len(t3.children[2].children[0].children) == 0 | |
| t4 = build_tree("(((())))") | |
| assert len(t4.children) == 1 | |
| assert len(t4.children[0].children) == 1 | |
| assert len(t4.children[0].children[0].children) == 1 | |
| assert len(t4.children[0].children[0].children[0].children) == 0 | |
| if __name__ == '__main__': | |
| main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment