ernie ernie - 4 months ago 26
Python Question

binary tree issue: unorderable types: str() < int()

I am trying to create a binary tree. I am testing what I have with the test code at the bottom but I receive the error message "elif var < here._variable:
TypeError: unorderable types: str() < int()" any insight would be great

class vartree:

class Node:

__slots__= "_left", "_value", "_variable", "_right"
def __init__ (self, l, var,val,r):
self._left = l
self._variable = var
self._value = val
self._right = r

def __init__(self):
self._root = None

def _search (self, here, var):
if here is None:
return self.Node(None, var, '0', None)

elif var < here._variable:
return self._search(here._left, var)

elif var > here._variable:
return self._search(here._right, var)

return here._value

def _insert(self, here, var, val):
if here is None:
return self.Node(None, val, var, None)

elif var < here._variable:
return self.Node(self._insert(here._left, var, val), here._value, here._variable, here._right)

elif var > here._variable:
return self.Node(here._left , here._value, here._variable, self._insert(here._right, var, val))

return var

def assign(self, var, val):
self._root = self._insert(self._root, var, val)
#self._insert(self._root, var, val)

def lookup(self, var):
return self._search(self._root, var)

if __name__ == "__main__":
T = vartree()


The problem is that one is an integer and the other a string at the line at which error occurs. After analyzing your code, i think i know why this is happening. Do this:

In your _insert() function, change this line:

  return self.Node(None, val, var, None)

to this:

return self.Node(None, var, val, None)

Hope this help :)