views:

631

answers:

2

I am struggling to get to know how to code a basic implementation using a dictionary and in-order traversal binary search tree in Python. The class have to be using the below structure.

I would be very happy if someone could fill out the blanks (pass) in each function to get me started.

class Dictionary:

    def __init__ (self):

        pass

    def insert (self, key, value):

        pass

    def delete (self, key):

        pass

    def find (self, key):

        pass

    def traverse (self, f):

        pass

    def __str__ (self):

        return str(self)
A: 
class Dictionary:
    def __init__ (self):
        self.data = {}
    def insert (self, key, value):
        self.data[key] = value
    def delete (self, key):
        if key in self.data:
            del self.data[key]
    def find (self, key):
        if key in self.data:
            return self.data[key]
        return None
    def traverse (self, f):
        for key,value in self.data:
            f(key,value)
    def __str__ (self):
        return str(self)
Will
Man, this is cheap!
Max Shawabkeh
subtle bugs included
Will
Endless recursion in `__str__`, missing `.items()` in `traverse`.
AndiDog
Isn't a binary tree; traversal is not "in-order" (OP didn't say what order he meant, but presumably sorted order, since that's what binary trees give you). If you don't want to answer homework, I'm with you, but don't give deliberately bogus answers. Python's dictionaries are not binary trees.
Glenn Maynard
This is NOT a homework, I am not even a student, I am just trying to learn Python by myself on my spare time. Is there anyone that would be kind enough to help me out. What is wrong with the above code, what should it look like? Thankful for all help!
Jonathan Clark
A: 

binary tree

You may want to use the array representation of a binary tree. Python has a powerful list data type which will make most of the work trivial. :)

class BinaryTree():
  def __init__(self):
     self.nodes = []

Here, that's a foundation you can start from.

badp
I mean, you do want to implement a binary tree, right? <.<
badp
Yes, I want to implement a dictionary class using a binary search tree.
Jonathan Clark