Python Binary Search Tree Issue - University Assignment

I’m working on a university project to create a supermarket management system in Python, where I’m using a binary tree to create stores and store products and their quantities. However, I’m facing an issue with product lookup in the tree.

The problem is that when I try to query a product that exists, the system isn’t returning the product name correctly, even when the product is in the tree. The code seems to be working correctly, but there’s something wrong with the search function.

Here’s the search function in my binary tree:
class Node:

    def __init__(self, product, quantity):
        self.product = product
        self.quantity = quantity
        self.left = None
        self.right = None

class SupermarketTree:
    def __init__(self, numSupermercado):
        self.numSupermercado = numSupermercado
        self.root = None

    def insert(self, product, quantity):
        if self.root is None:
            self.root = Node(product, quantity)
        else:
            self._insert_recursive(self.root, product, quantity)

    def _insert_recursive(self, node, product, quantity):
        if product < node.product:
            if node.left is None:
                node.left = Node(product, quantity)
            else:
                self._insert_recursive(node.left, product, quantity)
        else:
            if node.right is None:
                node.right = Node(product, quantity)
            else:
                self._insert_recursive(node.right, product, quantity)

    def search(self, product):
        return self._search_recursive(self.root, product)

    def _search_recursive(self, node, product):
        if node is None:
            return None
        if product == node.product:
            return node
        elif product < node.product:
            return self._search_recursive(node.left, product)
        else:
            return self._search_recursive(node.right, product)

class SupermarketSystem:
    def __init__(self):
        self.supermarkets = {}

    def acrescenta(self, numSupermercado, product, quantidade):
        if numSupermercado in self.supermarkets:
            self.supermarkets[numSupermercado].insert(product, quantidade)
        else:
            self.supermarkets[numSupermercado] = SupermarketTree(numSupermercado)

    def consulta(self, numSupermercado, product):
        if numSupermercado in self.supermarkets:
            supermarket = self.supermarkets[numSupermercado]
            result_node = supermarket.search(product)
            if result_node:
                return f"Product: {result_node.product}, Quantity: {result_node.quantity}"
            else:
                return "Product not found in the supermarket."
        else:
            return "Supermarket not found."

if __name__ == "__main__":
    system = SupermarketSystem()

    while True:
        print("Choose an operation:")
        print("1. Add Product")
        print("2. Query Product")
        print("3. Exit")

        choice = input("Enter the operation number: ")

        if choice == '1':
            market_number = int(input("Enter the supermarket number: "))
            product = input("Enter the product name: ")
            quantity = int(input("Enter the quantity: "))
            system.acrescenta(market_number, product, quantity)
            print(f"Product '{product}' added with quantity {quantity} to supermarket {market_number}.")

        elif choice == '2':
            market_number = int(input("Enter the supermarket number: "))
            product = input("Enter the product name: ")
            result = system.consulta(market_number, product)
            print(result)

        elif choice == '3':
            print("Exiting the program.")
            break

        else:
            print("Invalid operation. Please try again.")

I’ve already tried trimming extra spaces and converting strings to lowercase before comparison, but I’m still not getting the expected result.

Could someone please help me identify the issue and suggest a fix so that the search function correctly returns the product name when the product is in the tree?

Thank you in advance for your assistance!

When adding a product to a supermarket that does not exist, the supermarket gets created

else:
            self.supermarkets[numSupermercado] = SupermarketTree(numSupermercado)

but the product does not get added to it. Compare to the case that the supermarket exists

if numSupermercado in self.supermarkets:
            self.supermarkets[numSupermercado].insert(product, quantidade)

Thank you so mucH! I was trying to find this for like an hour you are a legend now it works perfectly!

Glad there is a quick solution.

Idle question: why use a binary tree to store/locate products and not some indexed access structure/mechanism, eg Python dict or RDBMS-index?

For a binary tree to have O(log2(n)) performance you have to balance the tree.
The worst case for your implementation is O(n) when products are added in sorted order.
I will leave it to you to research this issue and its solutions.

I appreciate your insights regarding the importance of balanced binary trees for optimized search performance. I completely understand the significance of tree balancing for real-world applications. However, in this specific context, I’m implementing these structures primarily for educational purposes, focusing on measuring and comparing execution times of different tree types. While balancing is crucial in practice, my current implementation serves the purpose of illustrating the basic concepts. Thanks for your valuable input!

I’m implementing these structures primarily for educational purposes, focusing on measuring and comparing execution times of different tree types.

Measuring the performance of an algorithm with implementation issues will give misleading comparison data. I do not see how any execution time measurement will be of value.