Ошибка при добавлении слова в дерево из списка значений

import random
import time
import math


def load_words():
    with open('big_words.txt') as word_file:
        list1 = word_file.readlines()
        list1 = [line.rstrip() for line in list1]
    return list1

class node:
    def __init__(self, value = None):
        self.value = value
        self.left_child= None
        self.right_child= None
        self.parent= None # указатель на род. узел в дереве

class binary_search_tree:
    def __init__(self):
        self.root = None

    def insert(self, value):
        if self.root == None:
            self.root = node(value)
        else:
            self._insert(value, self.root)

    def _insert(self, value, cur_node):
        if value < cur_node.value:
            if cur_node.left_child == None:
                cur_node.left_child = node(value)
                cur_node.left_child.parent = cur_node # установаливаем род
            else:
                self._insert(value, cur_node.left_child)
        elif value > cur_node.value:
            if cur_node.right_child == None:
                cur_node.right_child = node(value)
                cur_node.right_child.parent = cur_node # установаливаем род
            else:
                self._insert(value,cur_node.right_child)
                # если уже есть данный эл, то не добавляем

    def search(self, value):
        if self.root != None:
            return self._search(value, self.root)
        else:
            return False

    def _search(self, value, cur_node):
        if value == cur_node.value:
            return True
        elif value < cur_node.value and cur_node.left_child != None:
            return self._search(value, cur_node.left_child)
        elif value > cur_node.value and cur_node.right_child != None:
            return self._search(value, cur_node.right_child)
        return False 

tree = binary_search_tree()

list1 = load_words()

for i in range(len(list1)):
    tree.insert(list1[i])

В текстовом файле содержатся английские слова (каждое слово с новой строки)

Ошибка:

Traceback (most recent call last):
  File "_pydevd_bundle/pydevd_cython.pyx", line 1557, in _pydevd_bundle.pydevd_cython.ThreadTracer.__call__
RecursionError: maximum recursion depth exceeded
Traceback (most recent call last):
  File "_pydevd_bundle/pydevd_cython.pyx", line 1557, in _pydevd_bundle.pydevd_cython.ThreadTracer.__call__
RecursionError: maximum recursion depth exceeded while calling a Python object

Если добавлять значения не из текстового файла, то все работает:

list1 = ["hello", "hi", "apple"]
tree.insert(list1[0])
tree.insert(list1[1])
tree.insert(list1[2])

print(tree.search("apple"))
print(tree.search("hello"))
print(tree.search("hi"))
print(tree.search("apple1"))

Ответы (1 шт):

Автор решения: Danis

Функция load_words возвращает объект типа set вероятнее всего вы это сделали чтобы оставить только уникальные значения. У setнельзя брать элементы по индексу поэтому превратите его в список

def load_words():
    with open('big_words.txt') as word_file:
        valid_words = set(word_file.read().split())

    return list(valid_words)
→ Ссылка