Hasli4

Untitled

Jun 13th, 2025
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.37 KB | None | 0 0
  1. import re
  2.  
  3. INPUT_FILE = 'input.txt'
  4.  
  5. class Node:
  6. def __init__(self, data=None):
  7. self.data = data
  8. self.left = None
  9. self.right = None
  10.  
  11. def ensure_path(self, code, prompt_final):
  12. """
  13. Спускаемся по коду code от self.
  14. - Промежуточные узлы (всегда) создаём с запросом пользовательского ввода.
  15. - Конечный узел (последний символ) создаём:
  16. - если prompt_final=True → с запросом,
  17. - если False → автоматически (без запроса).
  18. Возвращает узел на конце пути.
  19. """
  20. node = self
  21. for i, c in enumerate(code):
  22. last = (i == len(code)-1)
  23. if c == '0':
  24. child = node.left
  25. if child is None:
  26. # если это не финальный шаг — или финальный, но prompt_final
  27. if not last or prompt_final:
  28. while True:
  29. val = input(f"Введите число для узла '{code[:i+1]}' (лево от '{code[:i]}'): ").strip()
  30. if val.isdigit():
  31. child = Node(int(val))
  32. break
  33. print("Нужно целое неотрицательное число.")
  34. else:
  35. # автоматом создаём пустой узел
  36. child = Node()
  37. node.left = child
  38. node = child
  39. else: # c == '1'
  40. child = node.right
  41. if child is None:
  42. if not last or prompt_final:
  43. while True:
  44. val = input(f"Введите число для узла '{code[:i+1]}' (право от '{code[:i]}'): ").strip()
  45. if val.isdigit():
  46. child = Node(int(val))
  47. break
  48. print("Нужно целое неотрицательное число.")
  49. else:
  50. child = Node()
  51. node.right = child
  52. node = child
  53. return node
  54.  
  55. def insert_from_file(self):
  56. try:
  57. with open(INPUT_FILE, 'r', encoding='utf-8') as f:
  58. for lineno, line in enumerate(f, 1):
  59. txt = line.strip()
  60. if not txt:
  61. continue
  62. parts = txt.split()
  63. if len(parts)!=2 or not parts[0].isdigit() or any(ch not in '01' for ch in parts[1]):
  64. print(f"[{lineno}] Пропущена: ожидается '<число> <код>'")
  65. continue
  66. number, code = int(parts[0]), parts[1]
  67. # prompt_final=False: не спрашиваем для конечного узла
  68. node = self.ensure_path(code, prompt_final=False)
  69. if node.data is not None:
  70. print(f"[{lineno}] Ошибка: узел '{code}' уже = {node.data}")
  71. else:
  72. node.data = number
  73. except FileNotFoundError:
  74. print(f"Файл '{INPUT_FILE}' не найден.")
  75. exit(1)
  76.  
  77. def insert_manually(self):
  78. print("Ввод вручную (q — выход): <число> <код>")
  79. while True:
  80. s = input("> ").strip()
  81. if s.lower()=='q':
  82. break
  83. parts = s.split()
  84. if len(parts)!=2 or not parts[0].isdigit() or any(ch not in '01' for ch in parts[1]):
  85. print("Неверно, повторите.")
  86. continue
  87. number, code = int(parts[0]), parts[1]
  88. # prompt_final=True: спрашиваем и для конечного узла
  89. node = self.ensure_path(code, prompt_final=True)
  90. if node.data is not None:
  91. print(f"Ошибка: узел '{code}' уже = {node.data}")
  92. else:
  93. node.data = number
  94.  
  95. def collect(self, path="", out=None):
  96. if out is None:
  97. out = []
  98. out.append((path, self.data))
  99. if self.left:
  100. self.left.collect(path+"0", out)
  101. if self.right:
  102. self.right.collect(path+"1", out)
  103. return out
  104.  
  105. def print_tree(self, level=0):
  106. if self.right:
  107. self.right.print_tree(level+1)
  108. print(" "*level + f"-> {self.data}")
  109. if self.left:
  110. self.left.print_tree(level+1)
  111.  
  112.  
  113. # ===== 主逻辑 =====
  114. print("Построение дерева по кодам путей")
  115. mode = input("1 — из файла, 2 — ручной ввод: ").strip()
  116. root = Node(0)
  117.  
  118. if mode=='1':
  119. root.insert_from_file()
  120. else:
  121. root.insert_manually()
  122.  
  123. print("\nСписок узлов (путь : значение):")
  124. for path, val in root.collect():
  125. print(f"{path or 'root':>5} : {val}")
  126.  
  127. print("\nГоризонтальное представление:")
  128. root.print_tree()
  129.  
Advertisement
Add Comment
Please, Sign In to add comment