コード例 #1
0
class BSTtreeDict(BST):
    '''A BST-based implementation of a sorted dictionary'''
    def __init__(self):
       
        self._items = BST()
    
    def __getitem__(self,key):	
    	'''Returns the value associated with key or returns None if key does not exist.'''
        return self._items.find(key)

    def __setitem__(self, key, value):
    	self._items.add((key, value))
           
    def __contains__(self,key): 
        return self.__getitem__(key) != None

    def __str__(self):
        return str(self._items) 

    def __len__(self): 
        return len(self._items)   

    def __iter__(self): 
        return iter(self._items)

    def pop(self,key): 
        return self._items.remove(key) 
コード例 #2
0
ファイル: tests.py プロジェクト: vks4git/a3200-2015-algs
 def grade(self, array):
     bst = BST()
     for i in array:
         bst.add(i)
     array = sorted(array)
     ptr = 0
     for i in bst:
         self.assertEqual(i, array[ptr])
         ptr += 1
コード例 #3
0
ファイル: test_bst.py プロジェクト: johncip/data_structures
def test_inorder():
    nums = range(1, 200)
    random.shuffle(nums)
    bst = BST()
    for n in nums:
        bst.add(n)
    nums.sort()

    assert bst.inorder() == sorted(nums)
コード例 #4
0
def bstsort(l):
    arbol = BST()
    # Generamos nuestra estructura 
    # de datos auxiliar
    
    while l:
        # Vaciamos la lista en el arbol
        item = l.pop()
        arbol.add(item)
    
    l.extend(arbol.inorder())
コード例 #5
0
ファイル: main.py プロジェクト: carsonkrueger/My-Projects
def make_tree():
    from bst import BST

    bst = BST()
    f = open("around-the-world-in-80-days-3.txt")

    for line in f:
        # line.translate(str.maketrans('', '', string.punctuation))
        for letter in line:
            # print(letter.lower(), end="")
            bst.add(Pair(letter))

    return bst
コード例 #6
0
def input_data(file_name):
    try:
        with open(file_name, 'r') as file:
            stock = int(file.readline())
            hamsters_count = int(file.readline())
            hamster_bst = BST(lambda hamster:
                              (hamster.avarice, hamster.daily_norm))
            for line in file.readlines():
                daily_norm, avarice = line.split()
                hamster_bst.add(Hamster(int(daily_norm), int(avarice)))
        return stock, hamsters_count, hamster_bst
    except (FileNotFoundError):
        sys.exit(f'file "{file_name}" not found')
    except:
        sys.exit(f'check data in "{file_name}"')
コード例 #7
0
class TreeSet(object):
    """A tree-based implementation of a sorted set."""

    def __init__(self):
        self._items = BST()

    def __contains__(self, item):
        """Returns True if item is in the set or
        False otherwise."""
        return self._items.find(item) != None

    def add(self, item):
        """Adds item to the set if it is not in the set.""" 
        if not item in self:
            self._items.add(item)
コード例 #8
0
class BSTDict(BST):
    def __init__(self):
        self._table = BST()

    def __getitem__(self, key):
        """Returns the value associated with key or
        returns None if key does not exist."""
        entry = Entry(key, None)
        result = self._table.find(entry)
        if result == None:
            return None
        else:
            return result.getValue()


    def __setitem__(self, key, value):
        """Inserts an entry with key/value if key
        does not exist or replaces the existing value
        with value if key exists."""
        entry = Entry(key, value)
        result = self._table.find(entry)
        if result == None:
            self._table.add(entry)
        else:
            result.setValue(value)

    def __contains__(self, key):
        """Returns True if key in BSTDict otherwise returns False."""
        entry = Entry(key, None)
        result = self._table.find(entry)
        if result == None:
            return False
        else:
            return True

    def __len__(self):
        """Returns the length of the BST Dictionary"""
        return len(self._table)

    def __iter__(self):
        """Iterates through the key/values in the BST"""
        return iter(self._table)
        

    def __str__(self): 
        """Returns unordered string of the dictionary and associated values in tree format."""
        return str(self._table)
コード例 #9
0
ファイル: test_bst.py プロジェクト: Hk4Fun/algorithm_offer
    def test_add(self):
        bst = BST()
        bst.add(10)
        assert bst.root.val == 10
        assert bst.is_empty() is False
        assert bst.size == 1
        assert bst.levels == 1
        assert bst.serialize() == '10'
        assert bst.level_order() == [[10]]
        assert bst.pre_order() == [10]
        assert bst.in_order() == [10]
        assert bst.post_order() == [10]
        assert bst == BST(serialize='10')

        bst.add(1)
        assert bst.root.val == 10
        assert bst.is_empty() is False
        assert bst.size == 2
        assert bst.levels == 2
        assert bst.serialize() == '10,1,#'
        assert bst.level_order() == [[10], [1]]
        assert bst.pre_order() == [10, 1]
        assert bst.in_order() == [1, 10]
        assert bst.post_order() == [1, 10]

        bst.add(20)
        assert bst.root.val == 10
        assert bst.is_empty() is False
        assert bst.size == 3
        assert bst.levels == 2
        assert bst.serialize() == '10,1,20'
        assert bst.level_order() == [[10], [1, 20]]
        assert bst.pre_order() == [10, 1, 20]
        assert bst.in_order() == [1, 10, 20]
        assert bst.post_order() == [1, 20, 10]

        bst.add(5)
        bst.add(15)
        assert bst.root.val == 10
        assert bst.is_empty() is False
        assert bst.size == 5
        assert bst.levels == 3
        assert bst.serialize() == '10,1,20,#,5,15,#'
        assert bst.level_order() == [[10], [1, 20], [5, 15]]
        assert bst.pre_order() == [10, 1, 5, 20, 15]
        assert bst.in_order() == [1, 5, 10, 15, 20]
        assert bst.post_order() == [5, 1, 15, 20, 10]
コード例 #10
0
class BSTSet(UserSet):
    def __init__(self):
        self._bst = BST()

    def size(self):
        return self._bst.size()

    def is_empty(self):
        return self._bst.is_empty()

    def add(self, item):
        self._bst.add(item)

    def remove(self, item):
        self._bst.remove(item)

    def contains(self, item):
        return item in self._bst
コード例 #11
0
def make_tree():
    ''' A helper function to build the tree.
    
    The test code depends on this function being available from main.
    :param: None
    :returns: A binary search tree
    '''
    my_tree = BST()
    with open("D:\\UVU\\DavidBennett\\CS2420\\Mod5\\P5\\around-the-world-in-80-days-3.txt", "r") as f:
        paragraph = f.read()
        for letter in paragraph:
            if letter.isalnum():
                try:
                    letter_obj = my_tree.find(Pair(letter))
                    letter_obj.count += 1
                except ValueError:
                    my_tree.add(Pair(letter))
    # print(my_tree.inorder())
    return my_tree
コード例 #12
0
ファイル: test_bst.py プロジェクト: Hk4Fun/algorithm_offer
    def test_remove(self):
        bst = BST()
        with pytest.raises(ValueError):
            bst.remove(0)

        bst.add(10)
        with pytest.raises(ValueError):
            bst.remove(0)
        bst.remove(10)
        assert bst.is_empty() is True

        bst.add(10)
        bst.add(20)
        bst.add(15)
        bst.add(5)
        bst.add(7)
        bst.remove(10)
        assert bst.serialize() == '15,5,20,#,7,#,#'
        assert bst.size == 4
        assert bst.root.val == 15

        bst.remove(5)
        assert bst.serialize() == '15,7,20'
        assert bst.size == 3
        assert bst.root.val == 15

        bst.add(18)
        bst.remove(20)
        assert bst.serialize() == '15,7,18'
        assert bst.size == 3
        assert bst.root.val == 15

        bst.remove(7)
        assert bst.serialize() == '15,#,18'
        assert bst.size == 2
        assert bst.root.val == 15

        bst.remove(15)
        assert bst.serialize() == '18'
        assert bst.size == 1
        assert bst.root.val == 18
コード例 #13
0
    def test_SearchAndAddDepthTwo(self):
        bst = BST()
        bst.add(10)
        bst.add(15)
        bst.add(5)
        bst.add(3)
        bst.add(7)
        bst.add(13)
        bst.add(17)

        self.assertEqual(3, bst.search(3).data)
        self.assertEqual(7, bst.search(7).data)
        self.assertEqual(13, bst.search(13).data)
        self.assertEqual(17, bst.search(17).data)
コード例 #14
0
def make_tree():
    """ A helper function to build the tree.
    
    The test code depends on this function being available from main.
    :param: None
    :returns: A binary search tree
    """
    bst = BST()
    _set = set()
    set_add = _set.add
    with open('around-the-world-in-80-days-3.txt', 'r') as f:
        _list = []
        for line in f.readlines():
            _list.append(line.strip())
        _list = ''.join(_list)
        punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~`'''
        for char in _list:
            if char in punc:
                _list = _list.replace(char, "")
        _set = [x for x in _list if not (x in _set or set_add(x))]
        for letter in _set:
            bst.add(Pair(letter))
    return bst
コード例 #15
0
    def test_SearchAndAddDepthOne(self):
        bst = BST()
        bst.add(2)
        self.assertEqual(2, bst.search(2).data)

        bst.add(3)
        self.assertEqual(3, bst.search(3).data)

        bst.add(1)
        self.assertEqual(1, bst.search(1).data)
コード例 #16
0
ファイル: test_bst.py プロジェクト: Hk4Fun/algorithm_offer
 def test_contains(self):
     bst = BST()
     assert 1 not in bst
     bst.add(10)
     assert 10 in bst
     bst.add(20)
     bst.add(15)
     bst.add(5)
     assert 20 in bst
     assert 5 in bst
     assert 15 in bst
     assert 11 not in bst
コード例 #17
0
class BSTSet(SetBase):
    def __init__(self):
        self._bst = BST()

    def get_size(self):
        return self._bst.size()

    def is_empty(self):
        return self._bst.is_empty()

    def add(self, e):
        return self._bst.add(e)

    def contains(self, e):
        return self._bst.contains(e)

    def remove(self, e):
        return self._bst.remove(e)
コード例 #18
0
ファイル: test_bst.py プロジェクト: Hk4Fun/algorithm_offer
 def test_minimum_maximum(self):
     bst = BST()
     assert bst.minimum() is None
     assert bst.maximum() is None
     bst.add(10)
     assert bst.minimum() == 10
     assert bst.maximum() == 10
     bst.add(20)
     bst.add(15)
     bst.add(5)
     bst.add(7)
     assert bst.minimum() == 5
     assert bst.maximum() == 20
コード例 #19
0
ファイル: test_bst.py プロジェクト: Hk4Fun/algorithm_offer
 def test_remove_min(self):
     bst = BST()
     assert bst.remove_min() is None
     assert bst.is_empty() is True
     bst.add(10)
     assert bst.remove_min() == 10
     assert bst.is_empty() is True
     bst.add(10)
     bst.add(20)
     bst.add(15)
     bst.add(5)
     bst.add(7)
     assert bst.remove_min() == 5
     assert bst.remove_min() == 7
     assert bst.remove_min() == 10
     assert bst.root.val == 20
     assert bst.size == 2
     assert bst.remove_min() == 15
     assert bst.remove_min() == 20
     assert bst.is_empty() is True
コード例 #20
0
class SymbolTable:
    def __init__(self):
        self.__bst = BST()

    def add(self, value):
        return self.__bst.add(value)

    def get(self, value):
        return self.__bst.find(value)

    def getRoot(self):
        return self.__bst.getRoot()

    def setRoot(self, root):
        return self.__bst.setRoot(root)

    def getPosition(self, value):
        return self.__bst.findPosition(value)

    def getIndex(self, value):
        return self.__bst.findIndex(value)

    def __str__(self):
        return self.__bst.in_order()
コード例 #21
0
def main():
    bst = BST()
    bst.add(3)
    bst.add(7)
    bst.add(1)
    bst.inorder()
コード例 #22
0
from bst import BST
bt = BST()
bt.add(12)
print(bt.contains(12))
print(bt.contains(5))
コード例 #23
0
def build_BST(values):
    tree = BST()
    for val in values:
        tree.add(val)
    return tree
コード例 #24
0
ファイル: bst_test.py プロジェクト: benrprince/cs-261-bst
from bst import Student, BST

if __name__ == '__main__':
    bst1 = BST()
    bst1.add(5)
    bst1.add(9)
    bst1.add(1)
    print(bst1.in_order_traversal())

    bst2 = BST()
    bst2.add(Student(88, "Sasha"))
    bst2.add(Student(94, "Rachel"))
    bst2.add(Student(93, "Phil"))
    bst2.add(Student(85, "Mike"))

    in_order = bst2.in_order_traversal()
    for i in in_order:
        print(i)
コード例 #25
0
"""
The test tree should look like:
              hello
          are       world
       and        how    you
                    war
                  peace
"""
values = ['hello', 'world', 'how', 'are', 'you', 'war', 'and', 'peace']

print('original data ...')

mydata = BST()
for v in values:
    print(v, end=', ')
    mydata.add(v, v)  # v is both key and data
print()

mydata.print()

print('inorder traversal should be in sorted order ...')
print('the result should be : and, are, hello, how, peace, war, world, you')
print('the result is : ', end='')
for x in mydata:
    print(x, end=', ')
print()

print('search for "world", should be True : ', 'world' in mydata)
print('search for "and", should be True: ', 'and' in mydata)
print('search for "you", should be True : ', 'you' in mydata)
print('search for "me", should be False : ', 'me' in mydata)
コード例 #26
0
ファイル: app.py プロジェクト: yurtsiv/bst-visualizer
class App:
  bst = BST()

  def __init__(self, master):
    # open full screen
    master.wm_attributes('-zoomed', True)
    master.update()

    self.init_ui_elems(master)

  def init_ui_elems(self, master):
    master.grid_rowconfigure(0, weight=1)
    master.grid_columnconfigure(0, weight=1)

    # Canvas
    canvas_cont = Frame(master)
    self.bst_canvas = BSTCanvas(master, canvas_cont)
    canvas_cont.grid(row=0, sticky="WENS")

    # Toolbar & text ouput
    bottom_section = Frame(master, bd=5, relief=RIDGE)
    bottom_section.grid_columnconfigure(1, weight=3)
    bottom_section.grid_rowconfigure(0, weight=1)
    bottom_section.grid(row=1, sticky="WENS")

    # Toolbar
    toolbar_cont = Frame(bottom_section)
    self.toolbar = Toolbar(
      master,
      toolbar_cont,
      on_add_new_node=self.on_add_new_node,
      on_remove_node=self.on_remove_node,
      on_show_subtree=self.on_show_subtree,
      on_get_id=self.on_get_id,
      on_size_click=self.on_size_click,
      on_root_click=self.on_root_click,
      on_min_click=self.on_min_click,
      on_max_click=self.on_max_click,
      on_print_click=self.on_print_click,
      on_reset_click=self.on_reset_click
    )

    toolbar_cont.grid(row=0, column=0, sticky="WENS")

    # Text output
    text_output_cont = Frame(bottom_section)
    text_output_cont.grid_columnconfigure(0, weight=1)
    text_output_cont.grid_rowconfigure(1, weight=1)
    text_output_cont.grid(row=0, column=1, sticky="WENS")
    self.text_output = TextOutput(text_output_cont)

  def on_size_click(self):
    self.text_output.println(
      "Tree size: " + str(self.bst.size)
    )
  
  def on_root_click(self):
    self.text_output.println(
      "Root element: " + str(self.bst.root_key())
    )

  def on_min_click(self):
    self.text_output.println(
      "Min element: " + str(self.bst.min())
    )

  def on_max_click(self):
    self.text_output.println(
      "Max element: " + str(self.bst.max())
    )
  
  def on_print_click(self):
    str_repres= self.bst.to_string()
    self.text_output.println(
      'In-order: ' + str_repres['in_order'] + '\n' +
      'Pre-order: ' + str_repres['pre_order'] + '\n' +
      'Post-order: ' + str_repres['post_order']
    )

  def on_reset_click(self):
    self.bst = BST()
    self.bst_canvas.draw(self.bst)
    self.text_output.clear()

  def on_show_subtree(self, root_key):
    new_bst = self.bst.subtree(root_key)
    if new_bst:
      self.bst = new_bst
      self.bst_canvas.draw(self.bst)
    else:
      self.text_output.println('WARNING: There is no ' + str(root_key) + ' in the tree')

  def on_add_new_node(self, key):
    inserted = self.bst.add(key)
    if inserted:
      self.bst_canvas.draw(self.bst)
    else:
      self.text_output.println('WARNING: Node ' + str(key) + ' was not added since it already exists')

  def on_remove_node(self, key):
    removed = self.bst.remove(key)
    if removed:
      self.bst_canvas.draw(self.bst)
    else:
      self.text_output.println('WARNING: There is no ' + str(key) + ' in the tree')

  def on_get_id(self, key):
    id = self.bst.find(key)
    if id:
      self.text_output.println('ID of ' + str(key) + ': ' + str(id))
    else:
      self.text_output.println('WARNING: There is no ' + str(key) + ' in the tree')
コード例 #27
0
def createConcordance(inputFile, stopWords, outputFile):

    #declare data structures
    stopSet = HashSet(3500)
    dictionary = HashDictionary(10000)
    bst = BST()

    #declare regular expressions
    newLine = re.compile(r'\n')
    exprSpaces = re.compile(r'\s')
    dhyp = re.compile('--')
    notChars = re.compile('\W|-')
    
    #populate hashset with stop words
    stopWords = open(stopWords, 'r')
    for stop in stopWords:
        x = newLine.search(stop)
        stop = stop[:x.start()]
        if stop == "":
            break
        stopSet.add(stop)
    stopWords.close()
    
    #open the input and process into words
    f = open(inputFile, 'r')
    lineNum = 0
    while True:
        line = f.readline()
        lineNum += 1
        if line == "":
            break

        #split lines
        m = dhyp.split(line)
        alist = []
        for i in range(len(m)):
            g = exprSpaces.split(m[i])
            alist = alist + g
            
        #strip down to words
        print alist
        for word in alist:
            if word == None:
                pass
            else:
                word = string.lower(word)
                while True:
                    n = notChars.search(word)
                    if len(word) <= 0:
                        break
                    elif n != None:
                        if n.start() == 0:
                            word = word[n.end():]
                        else:
                            word = word[:n.start()]
                    else:
                        break
                            
                #check if word is stop word
                if not stopSet.contains(word) and len(word) > 0:
                    #if word isn't already in dictionary
                    if dictionary.search(word) == None:
                        linkedValue = LinkedIndexedList()
                        dictionary.store(word, linkedValue)
                        dictionary.search(word).append(lineNum)
                        bst.add(word)
                    #if the word is in the dictionary
                    else:
                        dictionary.search(word).append(lineNum)
    f.close()

    #open output and use BST to print out words
    #   in alphabetical order
    output = open(outputFile, 'w')
    lyst = bst.inorder()
    temp = None
    for item in lyst:
        temp = dictionary.search(item)
        output.write(item + " - " + str(temp)+"\n")
    output.close()
コード例 #28
0
from bst import BST, Node

bst = BST()
bst.add(3)
bst.add(4)
bst.add(6)
bst.add(8)
bst.add(1)
bst.add(9)
bst.add(2)
bst.add(12)
minimum = bst.findMin()
maximum = bst.findMax()
print(f'Min is: {minimum}')
print(f'Max is: {maximum}')