Пример #1
0
class TaskManager(object):
    """docstring forTaskManager."""

    def __init__(self):
        self.binarySearchTree = BinarySearchTree()
        print("Initing TaskManager")

    """Adding task ordered by priority"""
    """Maibe adding a check for autheticity of the object """
    def addTask(self,task):
        #print("Add Task")
        self.binarySearchTree.addTask(task)

    def __str__(self):
        print(self.binarySearchTree.printTree())
class BinarySearchTreeTest(unittest.TestCase):
    def setUp(self):
        self.tree = BinarySearchTree()

    def getRoot(self):
        root = Node(7, None)
        left = root.left = Node(4, root)
        right = root.right = Node(13, root)
        left.left = Node(1, left)
        left.right = Node(6, left)
        right.left = Node(10, right)
        right.right = Node(15, right)

        return root

    def test_find(self):
        root = self.getRoot()
        self.assertEqual(7, self.tree.find(7, root).key)
        self.assertEqual(13, self.tree.find(13, root).key)
        self.assertEqual(6, self.tree.find(6, root).key)
        self.assertEqual(10, self.tree.find(10, root).key)
        self.assertEqual(1, self.tree.find(0, root).key)
        self.assertEqual(1, self.tree.find(2, root).key)
        self.assertEqual(10, self.tree.find(8, root).key)
        self.assertEqual(15, self.tree.find(16, root).key)

    def test_next(self):
        root = self.getRoot()
        self.assertEqual(4, self.tree.next(self.tree.find(1, root)).key)
        self.assertEqual(7, self.tree.next(self.tree.find(6, root)).key)
        self.assertEqual(6, self.tree.next(self.tree.find(4, root)).key)
        self.assertEqual(10, self.tree.next(self.tree.find(7, root)).key)
        self.assertIsNone(self.tree.next(self.tree.find(15, root)))

    def test_rangeSearch(self):
        root = self.getRoot()
        self.assertEqual([6, 7, 10], self.tree.rangeSearch(5, 12, root))
        self.assertEqual([1], self.tree.rangeSearch(1, 3, root))
        self.assertEqual([], self.tree.rangeSearch(16, 20, root))

    '''
                7
            4       13
         1    6   10   15
          3
    '''

    def test_insert(self):
        root = self.tree.insert(7, None)
        root = self.tree.insert(4, root)
        root = self.tree.insert(13, root)
        root = self.tree.insert(1, root)
        root = self.tree.insert(6, root)
        root = self.tree.insert(10, root)
        root = self.tree.insert(15, root)
        root = self.tree.insert(3, root)

        self.assertEqual(7, root.key)
        self.assertEqual(4, root.left.key)
        self.assertEqual(13, root.right.key)
        self.assertEqual(1, root.left.left.key)
        self.assertEqual(6, root.left.right.key)
        self.assertEqual(10, root.right.left.key)
        self.assertEqual(15, root.right.right.key)
        self.assertEqual(3, root.left.left.right.key)

        result = []
        self.tree.toString(root, result)
        self.assertEqual([1, 3, 4, 6, 7, 10, 13, 15], result)

    def test_remove(self):
        root = self.tree.insert(7, None)
        root = self.tree.insert(4, root)
        root = self.tree.insert(13, root)
        root = self.tree.insert(1, root)
        root = self.tree.insert(6, root)
        root = self.tree.insert(10, root)
        root = self.tree.insert(15, root)
        root = self.tree.insert(3, root)
        self.tree.root = root

        for i in range(8):
            self.tree.remove(self.tree.root)
            result = []
            self.tree.toString(self.tree.root, result)
            print(result)
Пример #3
0
 def __init__(self):
     self.binarySearchTree = BinarySearchTree()
     print("Initing TaskManager")
def preOrderIter(root):
    ''' a much easier way, use a stack, push right first and then push left '''
    if not root: return
    s = Stack()
    s.push(root)
    while not s.isEmpty():
        curr = s.pop()
        print curr.value
        if curr.right:
            s.push(curr.right)
        if curr.left:
            s.push(curr.left)


bst = BinarySearchTree()
bst.put(6)
bst.put(3)
bst.put(4)
bst.put(7)
bst.put(9)
bst.put(2)
print bst
print '==== post recur ===='
postOrderRecur(bst.root)
print '==== post iter===='
postOrderIter(bst.root)
print '==== post iter 2===='
postOrderIter2(bst.root)
print '==== pre iter===='
preOrderIter(bst.root)
Пример #5
0
def bfsIterative(node):
    if node is None:
        return []
    res = []
    q = Queue()
    q.enqueue(node)
    while not q.isEmpty():
        tmp = q.dequeue()
        res.append(tmp.value)
        if tmp.left:
            q.enqueue(tmp.left)
        if tmp.right:
            q.enqueue(tmp.right)
    return res


bst = BinarySearchTree()
bst.put(5)
bst.put(2)
bst.put(4)
bst.put(3)
bst.put(1)
bst.put(8)
bst.put(7)
bst.put(9)
print bst

print "dfs iterative: ", dfsIterative(bst.root)
print "dfs recursive: ", dfsRecursive(bst.root)
print "bfs iterative: ", bfsIterative(bst.root)
Пример #6
0
from binarySearchTree import BinarySearchTree

bst = BinarySearchTree()
bst[17] = 10
bst[5] = 4
bst[3] = 3
bst[11] = 1
bst[9] = 2
bst[16] = 3
bst[7] = 4
bst[8] = 5

print("before deletion:", bst[5])
print("len(bst):", len(bst))
del bst[5]
print("after deletion:", bst[5])
print("len(bst):", len(bst))

####################
print('-' * 30)
print('root.key:', bst.root.key)
for key in bst:
    print(key)
Пример #7
0
def search_time(dic, d, Tree, orderedList=False):
    """
    Measures the time it takes to search word in the given list
    :param dic: the word (value of the node) to be searched
    :param d: the word list, it can be random or ordered list
    :param Tree: a tree object (can be BinarySearchTree or AVLTree)
    :param orderedList: a flag to indicate whether wList is an ordered list or not, by default is not
    :return: measured time from start to finish
    """
    size = len(d)
    if Tree == "AVLTree":
        tree = AVLTree()
    elif Tree == "BinarySearchTree":
        tree = BinarySearchTree()
    else:
        print("Unsupported tree type: {}".format(Tree))
        return 0
    if orderedList:
        list_str = 'ordered list'
    else:
        list_str = 'random list'

    try:
        for i in range(size):
            tree[i] = d[i]
    except RecursionError as e:
        print('Exception caught while building the {} with size {}: {}'.format(
            Tree, size, e))
        tree_dic.write(
            'Error in building {},  size {:5d}, {}, word: "{}"\n'.format(
                Tree, size, list_str, dic))
        return 0
    print('{}, height of tree: {}, size of tree: {}'.format(
        Tree, tree.height(tree.root), len(tree)))

    tree.set_balanceFactor()
    start = time.clock()
    try:
        if orderedList:
            dKey = tree.search_ordered_list(dic)
        else:
            dKey = tree.search_random_list(dic)
        if dKey:
            print('yes, {} is in tree, found at key {}'.format(dic, dKey))
        else:
            print("no, {} is not found in tree".format(dic))
    except RecursionError as e:
        print('Exception caught during search with size {}: {}'.format(
            size, e))
        tree_dic.write(
            'Error during search {}, size {:5d}, {}, word: "{}"\n'.format(
                Tree, size, list_str, dic))
        return 0
    stop = time.clock()
    d_time = stop - start
    print('Searching for word "{}" in size {} tree took {:5f} seconds'.format(
        dic, size, d_time))

    if dKey:
        word_str = 'word in tree'
    else:
        word_str = 'word not in tree'
    tree_dic.write(
        '\nSearch time: {:5f} seconds \n{}: size {}\n{}, word: "{}"\n'.format(
            d_time, list_str, size, word_str, dic))

    sizes = d_sizes
    this_size = sizes.index(size)
    if this_size < len(sizes) - 1:
        nextSize = sizes[this_size + 1]
        predict_bigO_time(size, d_time, nextSize)
    return d_time
class TelephoneBook:

    global linked, tree
    linked = LinkedList()
    tree = BinarySearchTree()

    #----------Handles insertion of a record into the hash table----------
    def insert(self, name, address, number):
        global linked
        index = abs(hash(name)) % hashnum
        if linked.get(name, index) is None:
            entry = PersonNode(name, address, number)
            linked.add(entry, index)
        else:
            updatePerson = linked.get(name, index)
            updatePerson.setAddress(address)
            updatePerson.setNumber(number)

    #----------Handles retrieval of a record from the hash table----------
    def retrieve(self, name):
        global linked
        index = abs(hash(name)) % hashnum
        return linked.get(name, index)

    # ----------Handles deletion of a record from the hash table----------
    def delete(self, name):
        global linked
        index = abs(hash(name)) % hashnum
        return linked.remove(name, index)

    #----------Displays the contents of the hash table----------
    def displayBook(self):
        for index in range(hashnum):
            print("\nTelephoneBook[" + str(index) + "] => "),
            linked.display(index)

    #----------Writes contents of hash table to output file----------
    def writeOutput(self):
        linked.printContents()

    '''
    ---------------------------------Methods for BST Below-----------------------------------------
    '''

    #----------Handles insertion of a record into the BST----------
    def bstInsert(self, name, address, number):
        global tree
        index = abs(hash(name)) % hashnum
        if tree.get(name, index) is None:
            entry = PersonNode(name, address, number)
            tree.add(entry, index)
        else:
            updatePerson = tree.get(name, index)
            updatePerson.setAddress(address)
            updatePerson.setNumber(number)

    #----------Handles retrieval of a record from the BST----------
    def bstRetrieve(self, name):
        index = abs(hash(name)) % hashnum
        return tree.get(name, index)

    #----------Handles deletion of a record from the BST----------
    def bstDelete(self, name):
        global tree
        index = abs(hash(name)) % hashnum
        return tree.remove(name, index)

    #----------Displays the entire BST contents----------
    def bstDisplayBook(self):
        print("-----------------------------------------")
        tree.display(tree.root)
        print("-----------------------------------------")

    #----------Writes contents of BST to output file----------
    def bstWriteOutput(self):
        tree.printContents(tree.root)
Пример #9
0
'''
Arbol binario es una estructura 
de datos en la cual cada nodo puede
tener un hijo izquierdo y un hijo 
derecho, no pueden tener mas de dos hijos.
reglas:
-siempre hay una raiz
-todos los datos menores van a la izq
 todos los datos mayores van a la der
Recorrer: preorden, postorden
'''
from binarySearchTree import BinarySearchTree

tree = BinarySearchTree()

tree.add(8)
tree.add(10)
tree.add(3)
tree.add(14)
tree.add(13)
tree.add(1)
tree.add(6)
tree.add(4)
tree.add(7)
'''
tree.show_in_order(tree.root)
print("*"*5)
tree.show_pos_order(tree.root)
print("*"*5)
tree.show_pre_order(tree.root)
'''
Пример #10
0
from binarySearchTree import BinarySearchTree

# using BST
binary_search_tree = BinarySearchTree()

#        3
#     /      \
#    2        5
#   / \      / \
#  1  2.5   4   6

binary_search_tree.insert(3)
binary_search_tree.insert(5)
binary_search_tree.insert(4)
binary_search_tree.insert(6)
binary_search_tree.insert(2)
binary_search_tree.insert(1)
binary_search_tree.insert(2.5)

# get maximum of our BST
print(f"get maximum of our BST: {binary_search_tree.getMaxValue()}")

# traverse BST in order, like: 1, 2, 2.5, 3, 4, 5, 6
print("traverse BST in order: ")
binary_search_tree.traverse()
Пример #11
0
            if treeNode.hasLeftChild():
                newNodes.append(treeNode.leftChild)
                nbVisitedNodes += 1
            if treeNode.hasRightChild():
                newNodes.append(treeNode.rightChild)
                nbVisitedNodes += 1
        nodesPerDepth.append(newNodes)
        currentNodes = newNodes
    return nodesPerDepth


##################
# Main() to test #
##################
if __name__ == '__main__':
    mytree = BinarySearchTree()
    mytree[3] = "red"
    mytree[4] = "blue"
    mytree[6] = "yellow"
    mytree[2] = "at"
    mytree[5] = "green"
    for i in mytree:
        print(i, mytree[i])

    nodesperDepth = getListofNodesPerDepth(mytree)
    if nodesperDepth == []:
        print("Tree is empty")
    else:
        for depth, nodes in enumerate(nodesperDepth):
            print("Depth {}".format(depth))
            for node in nodes:
Пример #12
0
from binarySearchTree import BinarySearchTree, Node

tree = BinarySearchTree()

tree.insert(tree.root, Node(34))

tree.insert(tree.root, Node(32))
tree.insert(tree.root, Node(39))

tree.insert(tree.root, Node(30))

print(tree.search(tree.root, 32))
print(tree.search(tree.root, 34))
print(tree.search(tree.root, 30))
print(tree.search(tree.root, 39))
Пример #13
0
from tree import Tree
from binarySearchTree import BinarySearchTree

t = Tree()
t.insert_root("A")
t.insert_left(t.root, "B")
t.insert_right(t.root, "C")
t.insert_left(t.root.left, "D")
t.insert_right(t.root.left, "E")
t.insert_left(t.root.right, "F")
print(t)


t2 = BinarySearchTree()
t2.insert(2)
t2.insert(5)
t2.insert(8)
t2.insert(11)
t2.insert(1)
t2.insert(7)
print(t2)
print(t2.inorder())
 def setUp(self):
     self.tree = BinarySearchTree()
from linkedlist import LinkedList
from binarySearchTree import BinarySearchTree

if __name__ == '__main__':
    linked_list = LinkedList()

    linked_list.append_node(55)
    linked_list.append_node(60)
    linked_list.append_node(65)
    # PROBLEM 3a
    linked_list.add_to_beginning(45)
    linked_list.add_to_beginning(43)
    linked_list.add_to_beginning(30)
    # PROBLEM 3b
    linked_list.contains_node(5)
    # PROBLEM 4
    tree = BinarySearchTree()
    # PROBLEM 4a
    tree.insert_node(10)
    tree.insert_node(5)
    tree.insert_node(3)
    tree.insert_node(13)
    tree.insert_node(11)

    tree.search_tree(5)
Пример #16
0
def loadWeights(objects,
                filepath=None,
                usePosition=True,
                tolerance=TOL,
                axisMult=None,
                swapParity=True,
                averageVerts=True,
                doPreview=False,
                meshNameRemapDict=None,
                jointNameRemapDict=None):
    '''
	loads weights back on to a model given a file
	'''

    #nothing to do...
    if not objects:
        print 'No objects given...'
        return

    if filepath is None:
        filepath = getDefaultPath()

    if not filepath.exists:
        print 'File does not exist %s' % filepath
        return

    start = time.clock()

    #setup the mappings
    VertSkinWeight.MESH_NAME_REMAP_DICT = meshNameRemapDict
    VertSkinWeight.JOINT_NAME_REMAP_DICT = jointNameRemapDict

    #cache heavily access method objects as locals...
    skinPercent = cmd.skinPercent
    progressWindow = cmd.progressWindow
    xform = cmd.xform

    #now get a list of all weight files that are listed on the given objects - and
    #then load them one by one and apply them to the appropriate objects
    objItemsDict = {}
    for obj in objects:
        items = []  #this holds the vert list passed in IF any
        if obj.find('.') != -1:
            items = [obj]
            obj = obj.split('.')[0]

        try:
            objItemsDict[obj].extend(items)
        except KeyError:
            objItemsDict[obj] = items

    numItems = len(objItemsDict)
    curItem = 1
    progressWindow(e=True,
                   title='loading weights from file %d items' % numItems)

    #load the data from the file
    miscData, joints, jointHierarchies, weightData = Path(filepath).unpickle()

    #build the search tree
    tree = BinarySearchTree(weightData)
    findMethod = tree.getWithin
    findMethodKw = {'tolerance': tolerance}

    if averageVerts:
        findMethod = tree.getWithinRatio
        findMethodKw = {'ratio': tolerance}

    #see if the file versions match
    if miscData[api.kEXPORT_DICT_TOOL_VER] != TOOL_VERSION:
        api.melWarning(
            "WARNING: the file being loaded was stored from an older version (%d) of the tool - please re-generate the file.  Current version is %d."
            % (miscData[api.kEXPORT_DICT_TOOL_VER], TOOL_VERSION))

    #the miscData contains a dictionary with a bunch of data stored from when the weights was saved - do some
    #sanity checking to make sure we're not loading weights from some completely different source
    curFile = cmd.file(q=True, sn=True)
    origFile = miscData['scene']
    if curFile != origFile:
        api.melWarning(
            'the file these weights were saved in a different file from the current: "%s"'
            % origFile)

    #remap joint names in the saved file to joint names that are in the scene - they may be namespace differences...
    missingJoints = set()
    for n, j in joints.iteritems():
        if not cmd.objExists(j):
            #see if the joint with the same leaf name exists in the scene
            idxA = j.rfind(':')
            idxB = j.rfind('|')
            idx = max(idxA, idxB)
            if idx != -1:
                leafName = j[idx + 1:]
                if objExists(leafName):
                    joints[n] = leafName
                else:
                    search = cmd.ls('%s*' % leafName, r=True, type='joint')
                    if search:
                        joints[n] = search[0]
                        print '%s remapped to %s' % (j, search[0])

    #now that we've remapped joint names, we go through the joints again and remap missing joints to their nearest parent
    #joint in the scene - NOTE: this needs to be done after the name remap so that parent joint names have also been remapped
    for n, j in joints.iteritems():
        if not cmd.objExists(j):
            dealtWith = False
            for jp in jointHierarchies[n]:
                if cmd.objExists(jp):
                    joints[n] = jp
                    dealtWith = True
                    break

            if dealtWith:
                print '%s remapped to %s' % (j, jp)
                continue

            missingJoints.add(n)

    #now remove them from the list
    [joints.pop(n) for n in missingJoints]

    #axisMults can be used to alter the positions of verts saved in the weightData array - this is mainly useful for applying
    #weights to a mirrored version of a mesh - so weights can be stored on meshA, meshA duplicated to meshB, and then the
    #saved weights can be applied to meshB by specifying an axisMult=(-1,1,1) OR axisMult=(-1,)
    if axisMult is not None:
        for data in weightData:
            for n, mult in enumerate(axisMult):
                data[n] *= mult

        #we need to re-sort the weightData as the multiplication could have potentially reversed things...  i could probably
        #be a bit smarter about when to re-order, but its not a huge hit...  so, meh
        weightData = sortByIdx(weightData)

        #using axisMult for mirroring also often means you want to swap parity tokens on joint names - if so, do that now.
        #parity needs to be swapped in both joints and jointHierarchies
        if swapParity:
            for joint, target in joints.iteritems():
                joints[joint] = str(names.Name(target).swap_parity())
            for joint, parents in jointHierarchies.iteritems():
                jointHierarchies[joint] = [
                    str(names.Name(p).swap_parity()) for p in parents
                ]

    for geo, items in objItemsDict.iteritems():
        #if the geo is None, then check for data in the verts arg - the user may just want weights
        #loaded on a specific list of verts - we can get the geo name from those verts
        skinCluster = ''
        verts = cmd.ls(cmd.polyListComponentConversion(items if items else geo,
                                                       toVertex=True),
                       fl=True)

        #do we have a skinCluster on the geo already?  if not, build one
        skinCluster = cmd.ls(cmd.listHistory(geo), type='skinCluster')
        if not skinCluster:
            skinCluster = cmd.skinCluster(geo, joints.values())[0]
            verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True),
                           fl=True)
        else:
            skinCluster = skinCluster[0]

        #if we're using position, the restore weights path is quite different
        vertJointWeightData = []
        if usePosition:
            progressWindow(e=True,
                           status='searching by position: %s (%d/%d)' %
                           (geo, curItem, numItems),
                           maxValue=len(verts))

            vCount = -1
            for vert in verts:
                vCount += 1
                pos = Vector(xform(vert, q=True, ws=True, t=True))
                foundVerts = findMethod(pos, **findMethodKw)

                #accumulate found verts
                jointWeightDict = {}
                for v in foundVerts:
                    for joint, weight in zip(v.joints, v.weights):
                        actualJoint = joints[joint]
                        weight += jointWeightDict.get(actualJoint, 0)
                        jointWeightDict[actualJoint] = weight

                #normalize the weights
                weightSum = float(sum(jointWeightDict.values()))
                if weightSum != 1:
                    for joint, weight in jointWeightDict.iteritems():
                        jointWeightDict[joint] = weight / weightSum

                #append the data
                vertJointWeightData.append((vert, jointWeightDict.items()))

                #deal with the progress window - this isn't done EVERY vert because its kinda slow...
                if vCount % 50 == 0:
                    progressWindow(e=True, progress=vCount)

                    #bail if we've been asked to cancel
                    if progressWindow(q=True, isCancelled=True):
                        progressWindow(ep=True)
                        return

            progressWindow(e=True, status='maya is setting skin weights...')
            setSkinWeights(skinCluster, vertJointWeightData)

        #otherwise simply restore by id
        else:
            progressWindow(e=True,
                           status='searching by vert name: %s (%d/%d)' %
                           (geo, curItem, numItems),
                           maxValue=len(verts))

            #rearrange the weightData structure so its ordered by vertex name
            weightDataById = {}
            [
                weightDataById.setdefault(i.getVertName(),
                                          (i.joints, i.weights))
                for i in weightData
            ]

            for vert in verts:
                #progressWindow(edit=True, progress=cur / num * 100.0)
                #if progressWindow(q=True, isCancelled=True):
                #progressWindow(ep=True)
                #return

                #cur += 1
                try:
                    jointList, weightList = weightDataById[vert]
                except KeyError:
                    #in this case, the vert doesn't exist in teh file...
                    print '### no point found for %s' % vert
                    continue
                else:
                    jointList = [joints[j] for j in jointList]
                    jointsAndWeights = zip(jointList, weightList)
                    skinPercent(skinCluster, vert, tv=jointsAndWeights)

        #remove unused influences from the skin cluster
        cmd.skinCluster(skinCluster, edit=True, removeUnusedInfluence=True)
        curItem += 1

    end = time.clock()
    api.melPrint('time for weight load %.02f secs' % (end - start))
Пример #17
0
 def __init__(self):
     BinarySearchTree.__init__(self)