コード例 #1
0
def sortedArrayToBST(nums):
    T = Tree()
    if len(nums) == 0:
        return T
    else:
        T.root = SubTreeSlove(nums, 0, len(nums) - 1)
    return T
コード例 #2
0
def test_Tree_CalculateValuesSubTree(tree, tree_sum, tree_avg, tree_median):
    t = Tree(tree)
    assert t.get_sum(full_tree=False,
                     sub_tree=t.root.right) == tree_sum, "Incorrect sum"
    assert t.get_mean(full_tree=False,
                      sub_tree=t.root.right) == tree_avg, "Incorrect average"
    assert t.get_median(
        full_tree=False,
        sub_tree=t.root.right) == tree_median, "Incorrect median"
コード例 #3
0
ファイル: SymbolTable.py プロジェクト: AleeArdelian/LFTC
class SymbolTable:
    def __init__(self):
        self._binaryTree = Tree()

    def add(self, value):
        return self._binaryTree.Insert(value)

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

    def PrintSymbolTable(self):
        print(self._binaryTree)
コード例 #4
0
 def createPopulation(lengthPopu, dephTree):
     population = []
     numbOperators = int(helper.calculateNumberOfNodes(dephTree - 1))
     numbLeaves = int(
         helper.calculateNumberOfNodes(dephTree)) - numbOperators
     for i in range(lengthPopu):
         chromOperators = helper.createRandomOperationList(numbOperators)
         chromNumbers = helper.createRandomNumbersList(numbLeaves)
         tree = Tree()
         tree.createFromList(chromOperators + chromNumbers)
         population.append(tree)
     return population
コード例 #5
0
    def test_tree(self):
        """Test that the tree structure is as expected: all nodes have correct parent and children.
        """
        tree = Tree()
        root = tree.add_root(1)
        left = root.add_left(2)
        right = root.add_right(3)

        self.assertEqual(None, root.parent)
        self.assertEqual(root, tree.root)
        self.assertEqual(left, tree.root.left)
        self.assertEqual(right, tree.root.right)
        self.assertEqual(root, left.parent)
        self.assertEqual(root, right.parent)
        self.assertEqual(None, left.left)
        self.assertEqual(None, left.right)
        self.assertEqual(None, right.left)
        self.assertEqual(None, right.right)
コード例 #6
0
ファイル: SymbolTable.py プロジェクト: ColdCipri/LFTC-Lab1
class SymbolTable:
    def __init__(self):
        self.__binaryTree = Tree()

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

    def __str__(self):
        return str(self.__binaryTree)
コード例 #7
0
    def __init__(self,
                 window_size,
                 embedding_size,
                 whole_size,
                 step_size=0.01,
                 Theta=None):
        self.window_size = window_size
        self.embedding_size = embedding_size
        self.whole_size = whole_size
        self.step_size = step_size
        # Theta
        if Theta is not None:
            self.Theta = Theta
        else:
            self.Theta = np.random.rand(self.whole_size, self.embedding_size)

        self.tree = Tree(self.whole_size, self.embedding_size)
        self.tree.growTree()
コード例 #8
0
    def breadth_first_test(self):
        """Test that the breadth first traversal returns nodes in the correct order: left to right, top to bottom;
        processing all nodes on a level from left to right before proceeding down a level.
            E.g.        1
                    2       3
                4     5   6     7
        """
        tree = Tree()
        root = tree.add_root(1)
        left = root.add_left(2)
        right = root.add_right(3)
        left.add_left(4)
        left.add_right(5)
        right.add_left(6)
        right.add_right(7)

        items = []
        for item in tree.breadth_first():
            items.append(item.data)

        self.assertEqual(items, [1, 2, 3, 4, 5, 6, 7])
コード例 #9
0
def main():
    inputArray = input().split()
    tree = Tree(inputArray)

    print("Iterative Preorder: ")
    iterativePreorder(tree)

    print("Iterative Inorder: ")
    iterativeInorder(tree)

    print("Iterative Postorder with 2 stacks: ")
    iterativePostorderWith2Stacks(tree)

    print("Iterative Postorder with 1 stack: ")
    iterativePostorderWith1Stack(tree)
コード例 #10
0
 def crossover(tree_1, tree_2, depth):
     numbNodes = helper.calculateNumberOfNodes(depth)
     crossPoint = random.randint(2, numbNodes - 1)
     #print("CrossPoint:", crossPoint, "Number nodes:", numbNodes)
     #print("Tree_1:", tree_1.creationList)
     #print("Tree_2:", tree_2.creationList)
     list_1 = tree_1.creationList[0:crossPoint] + tree_2.creationList[
         crossPoint:int(numbNodes)]
     list_2 = tree_2.creationList[0:crossPoint] + tree_1.creationList[
         crossPoint:int(numbNodes)]
     #print()
     #print("List_1:", list_1)
     #print("List_2:", list_2)
     newTree_1 = Tree()
     newTree_2 = Tree()
     newTree_1.createFromList(list_1)
     newTree_2.createFromList(list_2)
     return newTree_1, newTree_2
コード例 #11
0
ファイル: SymbolTable.py プロジェクト: ColdCipri/LFTC-Lab1
 def __init__(self):
     self.__binaryTree = Tree()
コード例 #12
0
"""
this file is used to test some home work,
there are many errors
"""
from BinaryTree import Tree

p = Tree()
q = Tree()
test1 = [1, 2]
test2 = [1, 2]
lq = len(test1)
lp = len(test2)
p.add(test1)
q.add(test2)

print(q.preorder(q.root))
p_node = p.root
q_node = q.root

def isSameTree(p, q):
    if p is None and q is None:
        return True
    if p is None or q is None:
        return False
    if p.item == q.item:
        return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
    else:
        return False
    
if isSameTree(p_node, q_node):
    print('True')
コード例 #13
0
#		   /   \
#		  10   30
#		 / \   / \
#		5  15 25 35
#	   /      \
#	  1        28

a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g
d.left = h
f.right = i

#EX-2: RETURN A LIST OF NODE VALUES FROM A TREE IN Breadth-first traversal ORDER:
#

tree = Tree(a)

e = tree.find_min()
c = tree.find_max()

d = tree.insert(Node(7))
f = tree.insert(Node(8))

# print(e)
# print(c)
print(d)
print(f)
コード例 #14
0
def test_Tree_RaisesStatisticsErrorOnEmptyTree(a):
    t = Tree(a)
    assert t.get_sum(full_tree=True) == 0, "Incorrect sum"
    with pytest.raises(statistics.StatisticsError):
        t.get_median(full_tree=True)
        t.get_mean(full_tree=True)
コード例 #15
0
from BinaryTree import Tree
from BinaryTree import Node
import math
from Helper import helper
import random

print('-----Test generate a Tree-----')
tree = Tree()
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
tree.createFromList(data)
tree.printTree()

print('-----Test find a node-----')
node = tree.getListNodes()[7]
print('Node: ', node)
nodeFound = tree.find(node)
print('Parent node found: ', nodeFound)
nodeFound = tree.find(Node(6))
print('Parent node found: ', nodeFound)

print('----c-Test eval()-----')
x = 8
print(eval('((8)*(x))'))
print(eval('((9)*(math.sin((7)*(x))))'))
print(eval('(((8)*(x))+((0)*(x)*(1)*(x)))'))

print('-----Test number of Nodes-----')
print('Deph 1:', helper.calculateNumberOfNodes(1))
print('Deph 2:', helper.calculateNumberOfNodes(2))
print('Deph 3:', helper.calculateNumberOfNodes(3))
print('Deph 4:', helper.calculateNumberOfNodes(4))
コード例 #16
0
def test_Tree_CalculateValuesFullTree(tree, tree_sum, tree_avg, tree_median):
    t = Tree(tree)
    assert t.get_sum(full_tree=True) == tree_sum, "Incorrect sum"
    assert t.get_mean(full_tree=True) == tree_avg, "Incorrect average"
    assert t.get_median(full_tree=True) == tree_median, "Incorrect median"
コード例 #17
0
def test_Tree_RaisesTypeErrorWhenInvalidRootOnInit(a):
    with pytest.raises(TypeError):
        _ = Tree(a)
コード例 #18
0
def test_Tree_HandlesLoops():
    a = Node(5)
    t = Tree(Node(3, Node(3, a), a))
    assert t.get_sum(full_tree=True) == 11, "Incorrect sum"
コード例 #19
0
def main():
    inputArray = input().split()
    tree = Tree(inputArray)
    levelOrderTraversal(tree)
コード例 #20
0
class SkipGram(object):
    '''
    An implementation of Skip-Gram model, using Hierarchical Softmax.
    '''
    def __init__(self,
                 window_size,
                 embedding_size,
                 whole_size,
                 step_size=0.01,
                 Theta=None):
        self.window_size = window_size
        self.embedding_size = embedding_size
        self.whole_size = whole_size
        self.step_size = step_size
        # Theta
        if Theta is not None:
            self.Theta = Theta
        else:
            self.Theta = np.random.rand(self.whole_size, self.embedding_size)

        self.tree = Tree(self.whole_size, self.embedding_size)
        self.tree.growTree()

    def __call__(self, target_index):
        '''
        Evaluate the output from SkipGram model.
        target_index: The index will be used to generate a vector,
                    and then the vector is used to run over the model.
        '''
        pass

    def get_Nodes_and_Phis(self, ui_index):
        '''
        Get Phis and corresponding nodes with respect to vi.
        OUTPUT:
            node_list: nodes on the route from the root to vi(vi excluded).
            phi_list: an (l*embedding_size) ndarray, with each row being the Phi 
                     of the corresponding node in node_list.
        '''
        node_list = self.tree.getNodeList(ui_index)
        Phi = np.empty((len(node_list), len(node_list[0].Phi)),
                       dtype=type(node_list[0].Phi))
        for i in range(len(node_list)):
            Phi[i] = node_list[i].Phi
        return node_list, Phi

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def lossfunc(self, ui_index, vi_index):
        '''
        ui_index: one of the indexes of vi's context
        vi_index: vi's index
        '''
        _, Phi = self.get_Nodes_and_Phis(ui_index)
        seq = self.tree.index2Bin(ui_index)
        d = np.fromiter(seq, dtype=float)
        loss = -np.sum([d[i] * np.log(self.sigmoid(np.vdot(Phi[i], self.Theta[vi_index])))\
                + (1 - d[i]) * np.log(1 - self.sigmoid(np.vdot(Phi[i], self.Theta[vi_index])))\
                    for i in range(len(d))])
        # loss=np.sum([np.log(1+np.exp(-np.vdot(Phi[i], self.Theta[vi_index]))) for i in range(len(d))])
        return loss

    def testloss(self, sampling_size=100):
        '''
        Using sampling to estimate the loss of the whole model.
        '''
        group = [None, None]
        group[0] = np.random.choice(range(self.whole_size), sampling_size)
        tmp = set(range(self.whole_size))
        tmp = tmp.difference(set(group[0]))
        group[1] = np.random.choice(list(tmp), sampling_size)
        return sum([self.lossfunc(i, j)
                    for i, j in zip(group[0], group[1])]) / sampling_size

    def testRMSE(self, a, b):
        tmp = self.Theta[a] - self.Theta[b]
        return np.sqrt(np.vdot(tmp, tmp))

    def testprob(self, vi_index):
        prob = np.empty(self.whole_size)
        for ui_index in range(self.whole_size):
            _, Phi = self.get_Nodes_and_Phis(ui_index)
            seq = self.tree.index2Bin(ui_index)
            d = np.fromiter(seq, dtype=float)
            prob[ui_index] = np.exp(np.sum([np.log(self.sigmoid(-1 * np.vdot(Phi[i], self.Theta[vi_index]))) \
                for i in range(len(d))]))
        return prob

    def fracfunc(self, ui_index, vi_index, Phi):
        '''
        Main part used to compute gradients for Phi and Theta.
        Gradient for Phi[i]: -fracvec[i]*Theta[vi_index]
        Gradient for Theta[vi_index]: -fracvec.T.dot(Phi)
        '''
        seq = self.tree.index2Bin(ui_index)
        d = np.fromiter(seq, dtype=float)
        fracvec = np.empty_like(d)
        for i in range(len(d)):
            fracvec[i] = d[i] - self.sigmoid(
                np.vdot(Phi[i], self.Theta[vi_index]))
        return fracvec.reshape((len(fracvec), 1))

    def update(self, ui_index, vi_index):
        '''
        Update ui and vi once.
        '''
        nodes_list, Phi = self.get_Nodes_and_Phis(ui_index)
        fracvec = self.fracfunc(ui_index, vi_index, Phi)
        seq = self.tree.index2Bin(vi_index)
        d = np.fromiter(seq, dtype=float)
        # UPDATE Phi in tree nodes
        for i in range(len(nodes_list)):
            neg_gradi = fracvec[i] * self.Theta[vi_index]
            nodes_list[i].Phi = nodes_list[i].Phi + self.step_size * neg_gradi
        # UPDATE self.Theta
        neg_grad = fracvec.T.dot(Phi)
        self.Theta[vi_index] = self.Theta[vi_index] + self.step_size * neg_grad

    def unit_train(self, unit, n_iter=100, showLoss=False):
        '''
        A unit is a subsequence of walk with size 2*window_size+1.
        Show the total loss before and after a train.
        '''
        w = self.window_size
        if showLoss:
            for i in range(w):
                print(i, 'Before', self.lossfunc(unit[i], unit[w]))
                for j in range(n_iter):
                    self.update(unit[i], unit[w])
                print(i, 'After:', self.lossfunc(unit[i], unit[w]))
            for i in range(w + 1, len(unit)):
                print(i, 'Before', self.lossfunc(unit[i], unit[w]))
                for j in range(n_iter):
                    self.update(unit[i], unit[w])
                print(i, 'After:', self.lossfunc(unit[i], unit[w]))
        else:
            for i in range(w):
                for j in range(n_iter):
                    self.update(unit[i], unit[w])
            for i in range(w + 1, len(unit)):
                for j in range(n_iter):
                    self.update(unit[i], unit[w])

    def walk_train(self, walk, unit_iter=100, showLoss=False):
        '''
        Train the model using a walk. 
        The main procedule contains flopping a window with size window_size and
            updating Phi and Theta on each window.
        walk: an numpy array with each of its elements being an index.
        '''
        w = self.window_size
        unit_size = 2 * w + 1
        for i in range(len(walk) - unit_size + 1):
            # print('walk', '[', i, ':', i+unit_size, ']')
            self.unit_train(walk[i:i + unit_size],
                            unit_iter,
                            showLoss=showLoss)
コード例 #21
0
ファイル: testTree.py プロジェクト: marianodominguez/samples
from BinaryTree import Tree
import random

mytree = Tree()
list = range(50);
random.shuffle(list)

print list

for i in list:
    mytree.put(i)


print "inorder: ", mytree.inorder(mytree.root);
print "preorder: ", mytree.preorder(mytree.root);
print "postorder: ",mytree.postorder(mytree.root);
print "Binary: " , mytree.binarySearch(9);
print "DFS: " , mytree.dfs(9);
print "BFS: ", mytree.bfs(9);
コード例 #22
0
from BinaryTree import Tree
"""
BinaryTree.py has been defined 
"""

p = Tree()
q = Tree()
test1 = [1, None, 2]
test2 = [1, 2]
p.add(test1)
q.add(test2)

p_node = p.root
q_node = q.root


def isSameTree(p, q):
    if p is None and q is None:
        return True
    if p is None or q is None:
        return False
    if p.item == q.item:
        return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
    else:
        return False


if isSameTree(p_node, q_node):
    print('True')
else:
    print('False')
コード例 #23
0
ファイル: main.py プロジェクト: theluanz/atendimento-upa
        if option2 == 1:
            print("\n" + space + "\n|     Cadastro de paciente     |\n" +
                  space + "\n")
            nome = str(input("Nome: "))
            sexo = str(input("Sexo\n[M]Masculino\n[F]Feminino\n "))
            cpf = str(input("CPF: "))
            rg = str(input("RG: "))
            dia = str(input("Dia Nascimento: "))
            mes = str(input("Mes Nascimento: "))
            ano = str(input("Ano Nascimento: "))
            ctsus = int(input("Cartao SUS: "))
            sintomas = str(input("Quais os sintomas: "))

            paciente = Pessoa(nome, sexo, cpf, rg, dia, mes, ano, ctsus,
                              sintomas)
            treePaciente = Tree(paciente)
            tmp = int(
                input(
                    "É prioritario? (Acima de 60 anos ou febre?)\n[0] Não \n[1] Sim "
                ))
            if tmp == 1:
                filaPrioritaria.inserirPrioritario(treePaciente)
                database.inserir(treePaciente)
            else:
                filadePessoas.inserir(treePaciente)
                database.inserir(treePaciente)
            time.sleep(0.5)
        else:
            print("Selecione de quem voce vai adicionar os pais: ")
            eu = database.searchByIndex()
            print("Selecione quem é o pai: ")