Пример #1
0
    def test_print_node(self):
        bst = BinarySearchTree()

        self.assertEqual(bst.min(), None)

        node_val1 = 6
        bst.add(node_val1)
        node_val2 = 4
        bst.add(node_val2)
        node_val3 = 10
        bst.add(node_val3)
        node_val4 = 16
        bst.add(node_val4)

        #    6
        #   / \
        #  4   10
        #       \
        #        16

        #self.assertEqual(bst.__str__(), "4 6 10")

        self.assertEqual(bst.root_node.__str__(), "4 6 10")
        self.assertEqual(bst.root_node.right_child.__str__(), "10 16")
        self.assertEqual(bst.root_node.right_child.right_child.__str__(), "16")
Пример #2
0
def test_multiple_adds():
    tree = BinarySearchTree()
    tree.add(3)
    tree.add(1)
    tree.add(9)
    tree.add(6)
    assert(len(tree) == 4)
Пример #3
0
    def test_iterator(self):

        bst = BinarySearchTree()

        self.assertEqual(bst.min(), None)

        node_val1 = 6
        bst.add(node_val1)
        node_val2 = 4
        bst.add(node_val2)
        node_val3 = 10
        bst.add(node_val3)
        node_val4 = 16
        bst.add(node_val4)

        #    6
        #   / \
        #  4   10
        #       \
        #        16

        ite = BinarySearchIterator(bst)
        self.assertEquals(ite.tree, bst)

        self.assertEquals(ite.next(), 4)
        self.assertEquals(ite.next(), 6)
        self.assertEquals(ite.next(), 10)
        self.assertEquals(ite.next(), 16)

        self.assertRaises(StopIteration, ite.next)
Пример #4
0
 def test_nonleaf_rightnone_delete(self):
     """ Try to delete non leaf node with no right child. """
     a = BinarySearchTree(7, 'Harry')
     a[8] = 'Ron'
     a[5] = 'Ginny'
     a[4] = 'Hermione'
     a.delete(5)
     self.assertTrue(a.inorder() == [(4, 'Hermione'), (7, 'Harry'), (8, 'Ron')])
Пример #5
0
    def test_multiple_element_get(self):
        """ Put mulitple items into an empty bst and test inorder. """
	a = BinarySearchTree()
	a.put(7, 'Harry')
	a[8] = 'Ron'
	a.put(4, 'Hermione')
	a[9] = 'Ginny'
        self.assertTrue(a[4] == 'Hermione')
Пример #6
0
 def test_multiple_leaf(self):
     """ Tree of single item. """
     a = BinarySearchTree()
     a[7] = 'Harry'
     a[8] = 'Ron'
     a.put(4, 'Hermione')
     a[9] = 'Ginny'
     self.assertFalse(a._get(7, a.root).isLeaf())
Пример #7
0
    def test_has_children(self):

        #    6
        #   / \
        #  4   10
        #       \
        #        16

        bst = BinarySearchTree()
        node_val1 = 6
        bst.add(node_val1)
        node_val2 = 4
        bst.add(node_val2)
        node_val3 = 10
        bst.add(node_val3)
        node_val4 = 16
        bst.add(node_val4)
        self.assertEqual(bst.size, 4)

        node = bst.root_node  # we have 6
        self.assertEqual(node.value, node_val1)
        self.assertTrue(node.has_left_child())
        self.assertEqual(node.left_child.value, node_val2)
        self.assertTrue(node.has_right_child())
        self.assertEqual(node.right_child.value, node_val3)

        node = node.left_child  # we have 4 now
        self.assertFalse(node.has_left_child())
        self.assertFalse(node.has_right_child())
Пример #8
0
def test_delete_without_children():
    tree = BinarySearchTree()
    tree.add(1)
    tree.add(3)
    tree.add(6)
    tree.delete(6)
    assert(tree.get(3).childcount() == 0)
Пример #9
0
def test_parent_pointer_after_delete():
    tree = BinarySearchTree()
    tree.add(1)
    tree.add(3)
    tree.add(6)
    tree.delete(3)
    assert(tree.get(6).parent.value == 1)
Пример #10
0
    def test_nonleaf_delete(self):
        """ Try to delete non leaf node with both children. """
        a = BinarySearchTree(7, 'Harry')
        a[8] = 'Ron'
        a[5] = 'Ginny'
        a[4] = 'Hermione'
        a[6] = 'Neville'

        """                     7 - Harry
                             /             \  
                       5- Ginny           8 - Ron
                       /      \  
                4-Hermione    6-Neville
        """

        a.delete(7)
        self.assertTrue(a.inorder() == [(4, 'Hermione'), (5, 'Ginny'), (6, 'Neville'), (8, 'Ron')])
        self.assertTrue(a.root.value == 'Neville')

        a[7] = 'Harry'
        self.assertTrue(a.inorder() == [(4, 'Hermione'), (5, 'Ginny'), (6, 'Neville'), (7, 'Harry'), (8, 'Ron')])

        a.delete(6)
        self.assertTrue(a.inorder() == [(4, 'Hermione'), (5, 'Ginny'), (7, 'Harry'), (8, 'Ron')])
        self.assertTrue(a.root.value == 'Ginny')
Пример #11
0
def main():

    a = BinarySearchTree()
    a.add(2, '')
    a.add(1, '')
    a.add(4, '')
    a.add(5, '')

    b = BinarySearchTree()
    b.add(5, '')
    b.add(2, '')
    b.add(3, '')

    print diff(a, b)
Пример #12
0
 def __init__(self, data, snp, sample_id):
     '''
     Construct a genotype set from data arrays:
     - snp: SNP metadata record array (contains chromosome, name, morgans, base-pair location)
     - data: a 3-D genotype data array: (individual x SNP x allele)
     - sample_id: genotyped individuals' ID set
     '''       
     # People's IDs
     self.sample_id = sample_id
     self.data = data
     self._num_snps = self.data.shape[0]
     self._num_samples = self.data.shape[1]
     self._snp_range = None
     
     # SNP metadata: SNP label, chromosome number, Genetic distance in Morgans, and
     # base pair location for each SNP
     self.snp = snp
     # Base-pair-location to snp-index map, lazily-initialized + cached
     base_pair = self.snp['base_pair']
     self._base_pair = base_pair  # np.array([int(base_pair)]) if base_pair.size == 1 else base_pair
     self._bp_to_snp = dict_invert(dict(enumerate(self._base_pair)))
     # Construct a BST for fast bp queries
     self._snp_tree = BinarySearchTree(values=self._base_pair[optimal_insertion_order(self._num_snps)])
     self._snp_index_tree = util.list_index_tree(self._base_pair)
     # A genetic map: lists the two allele letters corresponding to 1 and 2 for each SNP, according
     # their order in the self.snp array.
     self.map = []
     # General metadata, for easy handling of CGI data
     self.metadata = []
                 
     # samples for which the parent-of-origin phase is determined
     self.poo_phase = np.zeros((self._num_samples,), dtype=np.byte)
Пример #13
0
def test_delete_two_children():
    tree = BinarySearchTree()
    tree.add(1)
    tree.add(3)
    tree.add(6)
    tree.add(2)
    tree.delete(3)
    assert(tree.contains(3) is False)
    assert(len(tree) == 3)
Пример #14
0
def test_delete_root():
    tree = BinarySearchTree()
    tree.add(1)
    tree.add(3)
    tree.add(6)
    tree.add(2)
    tree.delete(1)
    assert(tree.root.value == 3)
Пример #15
0
    def test_add(self):

        bst = BinarySearchTree()
        self.assertEqual(bst.size, 0)

        node_val1 = 6
        bst.add(node_val1)

        self.assertEqual(bst.size, 1)

        node_val2 = 4
        bst.add(node_val2)
        node_val3 = 10
        bst.add(node_val3)
        node_val4 = 16
        bst.add(node_val4)
        self.assertEqual(bst.size, 4)
Пример #16
0
 def setUp(self):
     self.bst = BinarySearchTree(5)
     # Notice that we're using the interface method
     # to add values to the tree, rather than
     # manipulating the left and right attributes directly.
     self.bst.insert(5)
     self.bst.insert(10)
     self.bst.insert(15)
     self.bst.insert(20)
     self.bst.insert(25)
     self.bst.insert(30)
     self.bst.insert(30)
Пример #17
0
    def test_multiple_element_put_init_empty(self):
        """ Put mulitple items into an empty bst and test inorder. """
	a = BinarySearchTree()
	a.put(7, 'Harry')
	a[8] = 'Ron'
	a.put(4, 'Hermione')
        self.assertTrue(a.inorder() == [(4, 'Hermione'), (7, 'Harry'), (8, 'Ron')])
Пример #18
0
def test_balance():
    tree = BinarySearchTree()
    tree.insert(2)
    tree.insert(4)
    tree.insert(5)
    tree.insert(1)
    assert tree.balance() == -1
Пример #19
0
def test_depth():
    tree = BinarySearchTree()
    tree.insert(2)
    tree.insert(4)
    tree.insert(5)
    tree.insert(1)
    assert tree.depth() == 3
Пример #20
0
def test_size():
    tree = BinarySearchTree()
    tree.insert(2)
    tree.insert(4)
    tree.insert(5)
    tree.insert(1)
    assert tree.size() == 4
Пример #21
0
def main():

    name = sys.argv[1];

    for i in xrange(1, 11):
        fname = '../data/%d_catalog.txt' % i
        #read the catalog and load to a list
        phonebook = []
        append = phonebook.append

        with open(fname, 'r') as f:
            for l in f:
                if l:
                    append(Entry.fromline(l))

        #print 'phonebook contains %d entries' % len(phonebook)
        name_idx = BinarySearchTree()
        for i, e in enumerate(phonebook):
            name_idx.add(e.name, i)

        start = time.time()
        idxs = name_idx.get(name)
        bstelapsed = (time.time() - start) * 1000

        # let's sort the entries by name
        phonebook.sort(key=lambda e: e.name)

        # let' search for a non existing name using naive search
        start = time.time()
        idx = search.naive(phonebook, name)
        nelapsed = (time.time() - start) * 1000

        # the same using binary search
        bstart = time.time()
        idx = search.binary_search(phonebook, name)
        bselapsed = (time.time() - bstart) * 1000
        print '%d - naive: %g - binary: %g - bst: %g'\
              % (len(phonebook), nelapsed, bselapsed, bstelapsed)
Пример #22
0
def build_subsequence_tree(input_list):
    """
    Builds and returns a binary search tree containing elements of the
    sequence using the container class. Also returns the last element
    of a longest increasing subsequence. This way the length of a
    longest increasing subsequence and that sequence can easily be
    calculated.

    input: A list of integers. No repeats!
    output: An ordered pair (bst,longest)
            bst = The binary search tree representing subsequences
            longest = Is the last element of a longest increasing subsequence
                      in its container class.
    """
    # The last element of one of the longest increasing sbusequences
    longest = Element(input_list[0],1,None)
    # The binary search tree we'll use.
    bst = BinarySearchTree()
    # For each element of the input list, we generate an element
    # container class for the element to represent it's behavior as
    # the last element of an increasing subsequence. If this
    # subsequence is longer than any other calculated, we record this.
    for i in input_list:
        greatest_element_less_than_i = bst.find_greatest_key_less_than(i)
        # If it exists, put i in an element that points back to the
        # greatest element less than i. Record that the subsequence is
        # longer.
        if greatest_element_less_than_i != None:
            current = Element(i,
                              greatest_element_less_than_i.length+1,
                              greatest_element_less_than_i)
            bst.insert(current)
            # If this is now the longest increasing subsequence, keep
            # track of that.
            if current.length > longest.length:
                longest = current
        else: # This is the smallest element we've encountered so
              # far. Put it in the BST
            bst.insert(Element(i,1,None))
    return (bst,longest)
Пример #23
0
 def test_empty_bst(self):
     """ Simple bst init should return [] on traversal. """
     a = BinarySearchTree()
     self.assertTrue(a.inorder() == [])
Пример #24
0
Файл: test.py Проект: lalitzz/DS
  Q = deque()
  Q.append(root)
  for i in range(1, h):
    print_branches(branch_len, node_space, start_len, node_in_this_level, Q, print)
    branch_len = branch_len // 2 - 1
    node_space = node_space // 2 + 1
    start_len = branch_len + (3 - leve) + indent
    print_nodes(branch_len, node_space, start_len, node_in_this_level, Q, print)

    for i in range(node_in_this_level):
      curr_node = Q.popleft()
      if curr_node is not None:
        Q.append(curr_node.left)
        Q.append(curr_node.right)
      else:
        Q.append(None)
        Q.append(None)
    node_in_this_level *= 2
  print_branches(branch_len, node_space, start_len, node_in_this_level, Q, print)
  print_leaves(indent, level, node_in_this_level, Q, print)

B = BinarySearchTree()
B.insert(5)
B.insert(4)
B.insert(2)
B.insert(3)
B.insert(9)
B.insert(7)
print(height(B.root))
#pretty_print(B.root)
Пример #25
0
# The original runtime of the 2 "for loops" would be O(n^2)
# original runtime == 6.719 seconds
'''
original code
for name_1 in names_1:
    for name_2 in names_2:
        if name_1 == name_2:
            duplicates.append(name_1)

# Updated code with new runtime of under 2 seconds and O(n)
for name_1 in names_2:
    if names_1 == names_2:
        duplicates.append(names_1)
'''
bst = BinarySearchTree('names')
for name in names_1:
    bst.insert(name)
for names_2 in names_2:
    if bst.contains(names_2):
        duplicates.append(names_2)


end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish?  There are no restrictions on techniques or data
# structures, but you may not import any additional libraries that you did not write yourself.
Пример #26
0
 def test_delete_single(self):
     """
     Deleting the node of a single-level tree returns None.
     """
     bst = BinarySearchTree(5)
     self.assertIsNone(bst.delete(5))
Пример #27
0
 def test_is_leaf(self):
     """
     A node without children is a leaf node.
     """
     bst = BinarySearchTree(10)
     self.assertTrue(bst.is_leaf())
Пример #28
0
 def test_find_minimum_one(self):
     """
     A tree's 'minimum' node is the one with the smallest key.
     """
     bst = BinarySearchTree(10)
     self.assertEqual(bst, bst.minimum())
Пример #29
0
def test_depth_returns_depth_of_tree_zero():
    """Test depth method returns proper depth of tree of depth four."""
    bst = BinarySearchTree()
    assert bst.depth() == 0
Пример #30
0
__author__ = 'Udara'
from bst import BinarySearchTree, EmptyValue
##tree i use for testing http://puu.sh/dsvBN/dbe749f41d.png

def num_leaves(T):
    if T.is_empty():
        return 0
    elif T.left.is_empty() and T.right.is_empty():
        return 1
    else:
        return num_leaves(T.left) + num_leaves(T.right)


a = BinarySearchTree(10)
b = BinarySearchTree(5)
c = BinarySearchTree(20)

d = BinarySearchTree(3)
e = BinarySearchTree(7)

f = BinarySearchTree(18)
g = BinarySearchTree(22)

a.left = b
a.right = c

b.left = d
b.right = e

c.left = f
c.right = g
Пример #31
0
def test_tree_balance_returns_correctly():
    """Test balance function returns currect balance."""
    from bst import BinarySearchTree
    bst = BinarySearchTree()
    bst.insert(85)
    bst.insert(55)
    bst.insert(88)
    bst.insert(2)
    bst.insert(79)
    bst.insert(50)
    assert bst.balance() == 2
Пример #32
0
def bst():
    """Binary search tree."""
    return BinarySearchTree()
Пример #33
0
def test_breadth_first_order_empty_error():
    """Test that post order traversal throws index error when empty tree."""
    bst = BinarySearchTree()
    bst_traversal = bst.breadth_first()
    with pytest.raises(IndexError):
        next(bst_traversal)
Пример #34
0
def test_post_order_empty_error():
    """Test that post order traversal throws index error when empty tree."""
    bst = BinarySearchTree()
    bst_traversal = bst.post_order()
    with pytest.raises(StopIteration):
        next(bst_traversal)
Пример #35
0
def test_pre_order_empty_error():
    """Test that pre order traversal throws index error when empty tree."""
    bst = BinarySearchTree()
    bst_traversal = bst.pre_order()
    with pytest.raises(IndexError):
        next(bst_traversal)
Пример #36
0
class BSTTestCase(unittest.TestCase):
    def setUp(self):
        self.bst = BinarySearchTree()
        self.bst.add(20, "Value for 20")
        self.bst.add(12, "Value for 12")
        self.bst.add(3, "Value for 3")
        self.bst.add(7, "Value for 7")
        self.bst.add(29, "Value for 29")
        self.bst.add(11, "Value for 11")
        self.bst.add(33, "Value for 33")
        self.bst.add(19, "Value for 19")
        self.bst.add(56, "Value for 56")
        self.bst.add(27, "Value for 27")
        self.bst.add(39, "Value for 39")

        self.bst2 = BinarySearchTree()
        self.bst2.add(1, "Value for 1")
        self.bst2.add(2, "Value for 2")
        self.bst2.add(3, "Value for 3")
        self.bst2.add(4, "Value for 4")
        self.bst2.add(5, "Value for 5")

    def test_add(self):

        self.assertEqual(self.bst.size(), 11)
        self.assertEqual(self.bst2.size(), 5)

        self.bst.add(11, "Value for 11")
        self.assertEqual(self.bst.size(), 12)
        self.assertEqual(self.bst.search(11), "Value for 11")

        self.bst2.add(6, "Value for 6")
        self.assertEqual(self.bst2.size(), 6)
        self.assertEqual(self.bst2.search(6), "Value for 6")

    def test_inorder(self):
        self.assertListEqual(self.bst.inorder_walk(),
                             [3, 7, 11, 12, 19, 20, 27, 29, 33, 39, 56])

        self.assertListEqual(self.bst2.inorder_walk(), [1, 2, 3, 4, 5])
        self.bst2.add(6, "Value for 6")
        self.assertListEqual(self.bst2.inorder_walk(), [1, 2, 3, 4, 5, 6])

    def test_postorder(self):
        self.assertListEqual(self.bst.postorder_walk(),
                             [11, 7, 3, 19, 12, 27, 39, 56, 33, 29, 20])

        self.assertListEqual(self.bst2.postorder_walk(), [5, 4, 3, 2, 1])
        self.bst2.add(6, "Value for 6")
        self.assertListEqual(self.bst2.postorder_walk(), [6, 5, 4, 3, 2, 1])

    def test_preorder(self):
        self.assertListEqual(self.bst.preorder_walk(),
                             [20, 12, 3, 7, 11, 19, 29, 27, 33, 56, 39])

        self.assertListEqual(self.bst2.preorder_walk(), [1, 2, 3, 4, 5])
        self.bst2.add(6, "Value for 6")
        self.assertListEqual(self.bst2.preorder_walk(), [1, 2, 3, 4, 5, 6])

    def test_search(self):
        self.assertEqual(self.bst.search(3), "Value for 3")
        self.assertFalse(self.bst2.search(0))

        self.bst2.add(6, "Value for 6")
        self.assertEqual(self.bst2.search(6), "Value for 6")

    def test_remove(self):
        self.bst.remove(27)
        self.assertEqual(self.bst.size(), 10)

        self.bst2.remove(3)
        self.assertListEqual(self.bst2.inorder_walk(), [1, 2, 4, 5])
        self.assertListEqual(self.bst2.preorder_walk(), [1, 2, 4, 5])
        self.assertListEqual(self.bst2.postorder_walk(), [5, 4, 2, 1])

    def test_smallest(self):
        self.assertTupleEqual(self.bst.smallest(), (3, "Value for 3"))

        self.assertTupleEqual(self.bst2.smallest(), (1, "Value for 1"))
        self.bst2.add(0, "Value for 0")
        self.assertTupleEqual(self.bst2.smallest(), (0, "Value for 0"))

    def test_largest(self):
        self.assertTupleEqual(self.bst.largest(), (56, "Value for 56"))
        self.bst.add(57, "Value for 57")
        self.assertTupleEqual(self.bst.largest(), (57, "Value for 57"))

        self.assertTupleEqual(self.bst2.largest(), (5, "Value for 5"))
        self.bst2.remove(5)
        self.assertTupleEqual(self.bst2.largest(), (4, "Value for 4"))
Пример #37
0
class TestRange(unittest.TestCase):
    def setUp(self):
        self.bst = BinarySearchTree(5)
        # Notice that we're using the interface method
        # to add values to the tree, rather than
        # manipulating the left and right attributes directly.
        self.bst.insert(5)
        self.bst.insert(10)
        self.bst.insert(15)
        self.bst.insert(20)
        self.bst.insert(25)
        self.bst.insert(30)
        self.bst.insert(30)

    def test_simple(self):
        self.assertEqual(self.bst.list_range(4, 7), [5, 5])
        self.assertEqual(self.bst.list_range(12, 50), [15, 20, 25, 30, 30])

    def test_inclusive(self):
        self.assertEqual(self.bst.list_range(5, 15), [5, 5, 10, 15])
        self.assertEqual(self.bst.list_range(25, 30), [25, 30, 30])

    def test_simple_empty(self):
        self.assertEqual(self.bst.list_range(6, 7), [])
Пример #38
0
from bst import BinarySearchTree

B = BinarySearchTree()
B.add(1)
B.add(3)
B.add(4)

B.remove(2)
B.remove(3)

Пример #39
0
 def test_search_single_none(self):
     """
     Searching a single-level tree for a key that doesn't exist returns None.
     """
     bst = BinarySearchTree(5)
     self.assertIsNone(bst.search(-999))
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []  # Return the list of duplicates in this data structure

# Replace the nested for loops below with your improvements
# for name_1 in names_1:
#     for name_2 in names_2:
#         if name_1 == name_2:
#             duplicates.append(name_1)
name_tree = BinarySearchTree(names_1[0])
for name in names_1:
    name_tree.insert(name)
for name in names_2:
    if name_tree.contains(name):
        duplicates.append(name)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish?  Thare are no restrictions on techniques or data
# structures, but you may not import any additional libraries that you did not write yourself.
Пример #41
0
 def test_not_has_right_child(self):
     """
     A node without a right child returns False.
     """
     bst = BinarySearchTree(10)
     self.assertFalse(bst.has_right_child())
Пример #42
0
def full_bst():
    """Binary search tree with root value of 8."""
    bst = BinarySearchTree(8)
    bst.insert(3)
    bst.insert(10)
    bst.insert(1)
    bst.insert(6)
    bst.insert(4)
    bst.insert(7)
    bst.insert(14)
    bst.insert(13)
    return bst
Пример #43
0
 def test_insert_three_smaller_leftmost_leaf(self):
     """
     Inserting a node with a key that is less than the leftmost leaf node's
     key appends the new node as the leftmost leaf's left child.
          10                10
        /    \            /    \
       5      15    =>   5      15
      / \    /  \       / \    /  \
     2   7  12   17    2   7  12   17
                      /
                     1
     Hint: Recursion, if you didn't already, makes this easy.
     """
     bst = BinarySearchTree(10)
     bst.left = BinarySearchTree(5)
     bst.right = BinarySearchTree(15)
     bst.left.left = BinarySearchTree(2)
     bst.left.right = BinarySearchTree(7)
     bst.right.left = BinarySearchTree(12)
     bst.right.right = BinarySearchTree(17)
     child = BinarySearchTree(1)
     bst.insert(child)
     self.assertEqual(child, bst.left.left.left)
Пример #44
0
def test_root_node_none():
    """Test that the root node is none if no value put in."""
    bst = BinarySearchTree()
    assert not bst.root
Пример #45
0
def five_bst():
    """Binary search tree with root value of 5."""
    return BinarySearchTree(5)
Пример #46
0
 def test_instantiation(self):
     try:
         BinarySearchTree()
     except NameError:
         self.fail("could not instantiate")
Пример #47
0
# 이진 검색 트리 클래스 BinarySearchTree 사용

from enum import Enum
from bst import BinarySearchTree

Menu = Enum('Menu', ['삽입', '삭제', '검색', '덤프', '키의범위', '종료'])

def select_Menu() -> Menu:
    s = [f'({m.value}){m.name}' for m in Menu]
    while True:
        print(*s, sep = '  ', end='')
        n = int(input(': '))
        if 1 <= n <= len(Menu):
            return Menu(n) 

tree = BinarySearchTree()

while True:
    menu = select_Menu()

    if menu == Menu.삽입:
        key = int(input('삽입할 키 입력: '))
        val = input('삽입할 값 입력: ')
        if not tree.add(key, val):
            print('삽입에 실패')

    elif menu == Menu.삭제:
        key = int(input('삭제할 키 입력: '))
        tree.remove(key)

    elif menu == Menu.검색:
Пример #48
0
 def test_find(self):
     item = 5
     bst = BinarySearchTree(item)
     return_item = bst.find(item)
     self.assertEqual(item, return_item)
Пример #49
0
    def test_element_get_simple(self):
        """ Get simple element."""
	a = BinarySearchTree()
	a[7] = 'Harry'
        self.assertTrue(a.get(7) == 'Harry')
Пример #50
0
 def test_instantiation_with_value(self):
     fake_vlue = "fake"
     bst = BinarySearchTree(fake_vlue)
     self.assertEqual(fake_vlue, bst.value)
Пример #51
0
from bst import BinarySearchTree
x = 'a'
tree = BinarySearchTree()
tree.put(8,x)
tree.put(4,x)
tree.put(2,x)
tree.put(3,x)
tree.put(10,x)
tree.put(6,x)
tree.put(7,x)
Пример #52
0
 def test_new_insert_method(self):
     insertee = 10
     bst = BinarySearchTree()
     bst.insert(insertee)
     self.assertEqual(insertee, bst.value)
Пример #53
0
    def test_simple_parent(self):
        """ Check parent. """
        a = BinarySearchTree(7, 'Harry')
        a[8] = 'Ron'
	self.assertTrue(a._get(8, a.root).parent.value == 'Harry')
Пример #54
0
 def test_search_single_one(self):
     """
     Searching a single-level tree for a key that does exist returns that node / tree.
     """
     bst = BinarySearchTree(5)
     self.assertEqual(bst, bst.search(5))
Пример #55
0
def test_depth_function_returns_correctly():
    """Test that the depth function returns correct val."""
    from bst import BinarySearchTree
    bst = BinarySearchTree()
    bst.insert(85)
    bst.insert(55)
    bst.insert(88)
    bst.insert(2)
    bst.insert(79)
    bst.insert(50)
    assert bst.depth() == 4
Пример #56
0
def test_size_returns_size_of_tree_zero():
    """Test size method returns size of tree."""
    bst = BinarySearchTree()
    assert bst.size() == 0
 def __init__(self):
     BinarySearchTree.__init__(self)
Пример #58
0
    for node in children:
        sum_children += node.key
    return sum_children


def is_sum_tree(current_node):
    if current_node is None:
        return True
    return (sum_children(current_node) == current_node.key) \
            and is_sum_tree(current_node.left) \
            and is_sum_tree(current_node.right)


if __name__ == "__main__":
    print("Create a Binary Search Tree that is not a sum tree")
    bst = BinarySearchTree()
    test_list = [8, 3, 1, 6, 4, 7, 10, 14, 13, 14]
    print("Insert the elements from the following list:", test_list)
    for element in test_list:
        print("Insert", element)
        bst.insert(element)

    print("\nPrint the tree in Depth First order")
    bst.print_tree()
    assert is_sum_tree(bst.root) == False

    assert is_sum_tree(None)

    print("Create a Binary Tree")
    binary_tree = NArayTree(is_binary=True)
    test_list = [15, 4, 7]
Пример #59
0
"""
ASTR 598 HW 7
Brett Morris
"""
from __future__ import print_function # Python 2 compatibility

from bst import BinarySearchTree

# Generate some random integers:
import numpy as np
integers = np.random.randint(0, 1000, size=100).tolist()

bst = BinarySearchTree()

# Insert some random integers into the binary search tree:
for integer in integers:
    bst.insert(integer)

# Traverse that tree in order (notice they're in order, wahoo!)
print("Traverse:")
bst.traverse()

# Find min, max:
print("Min: {0}, max: {1}".format(bst.min(), bst.max()))
Пример #60
0
class Genotype(object):
    #---------------------------------------------
    # Constructors
    #---------------------------------------------
    def __init__(self, data, snp, sample_id):
        '''
        Construct a genotype set from data arrays:
        - snp: SNP metadata record array (contains chromosome, name, morgans, base-pair location)
        - data: a 3-D genotype data array: (individual x SNP x allele)
        - sample_id: genotyped individuals' ID set
        '''       
        # People's IDs
        self.sample_id = sample_id
        self.data = data
        self._num_snps = self.data.shape[0]
        self._num_samples = self.data.shape[1]
        self._snp_range = None
        
        # SNP metadata: SNP label, chromosome number, Genetic distance in Morgans, and
        # base pair location for each SNP
        self.snp = snp
        # Base-pair-location to snp-index map, lazily-initialized + cached
        base_pair = self.snp['base_pair']
        self._base_pair = base_pair  # np.array([int(base_pair)]) if base_pair.size == 1 else base_pair
        self._bp_to_snp = dict_invert(dict(enumerate(self._base_pair)))
        # Construct a BST for fast bp queries
        self._snp_tree = BinarySearchTree(values=self._base_pair[optimal_insertion_order(self._num_snps)])
        self._snp_index_tree = util.list_index_tree(self._base_pair)
        # A genetic map: lists the two allele letters corresponding to 1 and 2 for each SNP, according
        # their order in the self.snp array.
        self.map = []
        # General metadata, for easy handling of CGI data
        self.metadata = []
                    
        # samples for which the parent-of-origin phase is determined
        self.poo_phase = np.zeros((self._num_samples,), dtype=np.byte)

    @staticmethod
    def empty(snp, sample_id, sz):
        '''Allocate an empty data array of size sz.'''
        return Genotype(snp, sample_id, np.zeros(sz, dtype=np.byte))
    
    def copy(self):
        '''Return a deep copy of this object.'''
        return Genotype(self.data.copy(), self.snp.copy(), self.sample_id.copy())
    
    #---------------------------------------------
    # Operators
    #---------------------------------------------
    def __key(self):
        '''Uniquely-identifying key of this object.'''
        return (self.data.tolist(), self.snp.tolist(),
                self.sample_id.tolist() if self.sample_id is not None else None)

    def __eq__(self, y):
        '''Equality of objects.'''
        return self.__key() == y.__key()

    def __ne__(self, y):
        '''Inequality of objects.'''
        return self.__key() != y.__key()

    def __hash__(self):
        '''Object hash code.'''
        return hash(self.__key())

    def __repr__(self):
        return 'Genotype[snps=%d, samples=%d]' % (self.num_snps, self.num_samples)
     
    #---------------------------------------------
    # Methods
    #---------------------------------------------
    def clear(self, snp, person):
        '''Set the data for the individuals whose index is person at snp indices snp
        to MISSING.'''
        self.data[snp, person, :] = constants.MISSING
        
    def nearest_snp(self, bp):
        '''Nearest SNP neighbor to a base pair location bp.'''
        return util.nearest_neighbor_in_list_tree(bp, self._base_pair, self._snp_index_tree)

    def nearest_snp_multiple(self, bp):
        '''Nearest SNP neighbor to each element of a base pair collection bp.'''
        return util.nearest_neighbor_in_list_tree_multiple(bp, self._base_pair, self._snp_index_tree)

    def segment_intersect(self, segment_in_bp):
        '''Return endpoints of the SNP index range contained in the base-pair segment segment.
        If segment does not intersect our SNP range, return None. The range is [start_index,stop_index)
        where start=inclusive and stop is exclsive.'''
        left = self._snp_tree.find_smallest_ge(segment_in_bp[0])
        if left is None: return None
        right = self._snp_tree.find_largest_le(segment_in_bp[1])
        if right is None: return None
        return (self._bp_to_snp[left], self._bp_to_snp[right] + 1)

    def segments_intersect(self, segments_in_bp):
        '''Find SNP range of each segment in the list segments_in_bp whose unit is base pairs.'''
        segments = []
        for x in segments_in_bp:
            y = self.segment_intersect(x)
            if y is not None: segments.append(y)
        return segments
    
    def fill_fraction(self, snps=None, snp_range=None, sample=None, allele=None):
        '''Return the fraction of non-missing data in a sample. If snp_range is specified,
        it takes precedence to the iterable snps. If none is specified, all snps are considered.'''
        
        # TODO: replace by slice iterator
        if allele is not None:
            if sample is not None:
                d = self.data[snp_range[0]:snp_range[1], sample, allele] if snp_range is not None else (self.data[snps, sample, allele] if snps is not None else self.data[:, sample, allele])
            else:
                d = self.data[snp_range[0]:snp_range[1], :     , allele] if snp_range is not None else (self.data[snps, :     , allele] if snps is not None else self.data[:, :, allele])
        else:
            if sample is not None:
                d = self.data[snp_range[0]:snp_range[1], sample, :] if snp_range is not None else (self.data[snps, sample, :] if snps is not None else self.data[:, sample, :])
            else:
                d = self.data[snp_range[0]:snp_range[1], :     , :] if snp_range is not None else (self.data[snps, :     , :] if snps is not None else self.data)
        return 1.0 * np.size(np.where(d != constants.MISSING)[0]) / max(1, np.size(d))
    
    def data_of_snp(self, index):
        '''Return the genotype data of snp # index. index is 0-based.'''
        return self.data[index]

    #---------------------------------------------
    # Properties
    #---------------------------------------------
    @property
    def shape(self):
        '''Shape of the data array.'''  
        return self.data.shape

    @property
    def num_data(self):
        '''total # data entries.'''  
        return self.data.size
    
    @property
    def num_filled(self):
        '''# filled alleles.'''  
        return len(np.nonzero(self.data)[0])

    @property
    def num_missing(self):
        '''# missing alleles.'''  
        return len(np.where(self.data == constants.MISSING)[0])

# Redundant - cf. fill_fraction()
#    @property
#    def filled_fraction(self):
#        '''Total #filled / # haplotypes.'''  
#        return (1.0 * self.num_filled)/self.num_data

    @property
    def num_snps(self):
        '''#genotyped SNPs for each person.'''  
        return self._num_snps

    @property
    def num_samples(self):
        '''# genotyped people.'''  
        return self._num_samples

    @property
    def base_pair(self):
        '''Base pair locations.'''  
        return self._base_pair

    @property
    def snp_range(self):
        '''Find and cache the range of all SNPs.'''
        if self._snp_range is None: self._snp_range = np.arange(0, self.num_snps)
        return self._snp_range

    @property
    def aligned_samples(self):
        '''Return the list of samples whose parent-of-origin phase has been determined.'''
        return np.where(self.poo_phase)[0]