Sam C.
Sam C.

Reputation: 11

Python: Recursive Treap Insert Function cannot create new node

I am writing a Python program for my class and I have to create a function (_insert) which is supposed to recursively perform the insert operation into my Map which is a treap data structure. However, whenever I am checking in my base cases to see if the value/key of the current node is equal to some specific value, it return an AttributeError saying that either 'str' object has no attribute 'key' (in the case of key) or 'int' object has no attribute 'value' (in the case of value), I don't know why this would happen since I pass both the key and the value into each function call.

from collections import deque, defaultdict
from dataclasses import dataclass
from random      import random

@dataclass
class Node:
    ''' Node with string key, int value, float priority, and left and right children. '''
    key: str
    value: int
    priority: float
    left: 'Node' = None
    right: 'Node' = None
    
class Map:
     def __init__(self):
    self.root = None

     def insert(self, key, value, priority=None):
           try:
               self.root = self._insert(self.root,key,value)
           except ValueError:
               pass

    def _insert(self, node, key, value, priority=None):
        ''' Recursively insert key, value pair into Map. '''
        print("key",key)
        
        # Base case: Create new Node
        if node is None:
                new = Node(key,value,priority or random())
                return new
#               return Node(key, value, priority or random())
            
        if key == node.key: # If key is already in Map, then update value
            node.value = value
            
        # Base case: Found Match, so raise exception
        if value == node.value:
                raise ValueError
            
        if value <= node.value:                     # Recursive: BST insert left
            node.left = self._insert(node.left, key, value, priority)
            
            if node.left.priority > node.priority: # Check Max-Bin-Heap Invariant
                node = Map._rotate_right(node)
                
        else:                                       # Recursive: BST insert right
            node.right = Map._insert(node.right,key, value, priority)
            
            if node.right.priority > node.priority: # Check Max-Bin-Heap Invariant
                node = self._rotate_left(node)
        
        return node
    @staticmethod
    def _rotate_right(p):
        cl, gr   = p.left, p.left.right
        cl.right = p
        p.left   = gr
        return cl
        
    @staticmethod
    def _rotate_left(p):
        cr, gl  = p.right, p.right.left
        cr.left = p
        p.right = gl
        return cr

I don't even know how to address the issue.

Upvotes: 1

Views: 166

Answers (0)

Related Questions