Lekcja – Binary Search Tree – wprowadzenie

class Node:

    def __init__(self, id, data):
        self.id = id
        self.data = data
        self.left = None
        self.right = None
        self.depth = None

    def __repr__(self):
        return f"<{self.id}/{self.depth}>"

def insert(parent, child, depth=0):
    if parent is None:
        child.depth = depth
        return child
    elif parent.id == child.id:
        return parent
    elif child.id < parent.id:
        parent.left = insert(parent.left, child, parent.depth+1)
    else:
        parent.right = insert(parent.right, child, parent.depth+1)
    return parent

def load_stock_file(file_name):
    bst = None
    file = open(file_name, 'r')
    line = file.readline()
    line_number = 0

    while True: 
        line = file.readline()
        if not line:
            break
        data = line.split(',')
        line_number +=1
        print(line_number, data[0], '/', data[1])
        node = Node(data[0], data[1])
        bst = insert(bst, node)        

    file.close()
    return bst


# https://www.nasdaq.com/market-activity/stocks/screener?exchange=NASDAQ&render=download
stock_file = './data/stock.csv'

bst = load_stock_file(stock_file)
print('Done')

Lab

class City:

    def __init__(self, id, country, population):
        self.id = id
        self.country = country
        self.population = population
        self.left = None
        self.right = None
        self.depth = None

    def __repr__(self):
        return f"<{self.id}/{self.depth}>"



def insert(parent, child, depth=0):
    if parent is None:
        child.depth = depth
        return child
    elif parent.id == child.id:
        return parent
    elif child.id < parent.id:
        parent.left = insert(parent.left, child, parent.depth+1)
    else:
        parent.right = insert(parent.right, child, parent.depth+1)
    return parent



def load_file(file_name):
    bst = None
    file = open(file_name, 'r', encoding="utf-8")
    line = file.readline()
    line_number = 0

    while True: 
        line = file.readline()
        if not line:
            break
        data = line.split(',')
        line_number +=1

        city_ascii = data[1].strip().replace('"','').replace("'",'').replace("`",'').upper()
        country = data[4].replace('"','').replace("'",'').replace("`",'').upper()
        try:
            population = int(data[9].replace('"',''))
        except ValueError:
            population = -1

        print(line_number, city_ascii)
        node = City(city_ascii, country, population)
        bst = insert(bst, node)        

    file.close()
    return bst



# https://www.kaggle.com/juanmah/world-cities
stock_file = './data/worldcities.csv'

bst = load_file(stock_file)