def splay(self, node): self.num_operations += 1 if self.do_naive: while node.parent is not None: self.rotate(node) else: Tree.splay(self, node)
def test_insert(): # Test validity first tree = Tree() sequence = [pow(997, i, 1999) for i in range(1, 1999)] for elem in sequence: tree.insert(elem) assert flatten(tree) == sorted( sequence), "Incorrect tree after a sequence of inserts" # Test speed tree = Tree() for elem in range(200000): for _ in range(10): tree.insert(elem)
def deserialize_tree(string): def deserialize_node(i): assert string[i] == "(" i += 1 if string[i] == ")": return i + 1, None else: comma = string.find(",", i) comma2, left = deserialize_node(comma + 1) rparen, right = deserialize_node(comma2 + 1) assert string[rparen] == ")" return rparen + 1, Node(int(string[i:comma]), left=left, right=right) index, root = deserialize_node(0) assert index == len(string) return Tree(root)
def test_lookup(): tree = Tree() for elem in range(0, 1000, 2): tree.insert(elem) # Find non-existing for elem in range(1, 1000, 2): for _ in range(10): assert tree.lookup(elem) is None, "Non-existing element was found" # Find existing for elem in range(0, 1000, 2): for _ in range(10): assert tree.lookup( elem) is not None, "Existing element was not found"
def rotate(self, node): self.num_rotations += 1 Tree.rotate(self, node)
def __init__(self, naive=False): Tree.__init__(self) self.do_naive = naive self.reset()
def test_remove(): # Test validity first tree = Tree() for elem in range(2, 1999 * 2): tree.insert(elem) sequence = [2 * pow(997, i, 1999) for i in range(1, 1999)] for elem in sequence: tree.remove(elem + 1) # if flatten(tree) != sorted(sequence): # print(elem+1) # print(flatten(tree)) # print(sorted(sequence)) assert flatten(tree) == sorted( sequence), "Incorrect tree after a sequence of removes" # Test speed tree = Tree() for elem in range(0, 10000, 2): tree.insert(elem) # Non-existing elements for elem in range(1, 10000, 2): for _ in range(10): tree.remove(elem) # Existing elements for elem in range(2, 10000, 2): tree.remove(elem)