Exemplo n.º 1
0
class Distributor:
    def __init__(self, distributorName):
        self.distributorName = distributorName
        self.includes = BinarySearchTree()
        self.excludes = [BinarySearchTree()]

    def addIncludePermission(self, startID, endID, parentDistributorNode):
        if (parentDistributorNode == None):
            self.includes.insertNode(self.includes.root, startID, endID)
        else:
            isPresentInParentInclude = parentDistributorNode.includes.isInRange(
                parentDistributorNode.includes.root, startID, endID)
            isPresentInParentExclude = self.checkExcludes(
                parentDistributorNode, startID, endID)

            if (isPresentInParentInclude and not (isPresentInParentExclude)):
                self.includes.insertNode(self.includes.root, startID, endID)
            elif (isPresentInParentExclude):
                return 0
        return 1

    def checkExcludes(self, node, startID, endID):
        for i in range(len(node.excludes)):
            isPresent = node.excludes[i].isInRange(node.excludes[i].root,
                                                   startID, endID)
            if (isPresent):
                return isPresent
        return False

    def addExcludePermission(self, startID, endID):
        isPresent = self.includes.isInRange(self.includes.root, startID, endID)
        if (isPresent):
            self.excludes[0].insertNode(self.excludes[0].root, startID, endID)
            return 1
        else:
            return 0
Exemplo n.º 2
0
    def button_clicked(self):#кнопка подбора фильмов по жанру и году
        self.ui.listFilms.clear()
        T = BinarySearchTree()#создание объекта бинарного дерева поиска
        first = 0
        second = 0
        if not self.ui.firstYear.text().isdigit():#проверка на корректный ввод года
            first = 1920
        else: first = int(self.ui.firstYear.text())
        if not self.ui.secondYear.text().isdigit():#проверка на корректный ввод года
            second = 2019
        else: second = int(self.ui.secondYear.text())
        l =[[ "аниме",[]],["фэнтези",[]],["мелодрама",[]],["биография",[]],["боевик",[]],
            ["вестерн",[]],["военный",[]],["детектив",[]],["документальный",[]],["драма",[]],
            ["мультфильм",[]],["приключения",[]],["семейный",[]], ["триллер",[]], ["ужасы",[]],
            ["фантастика",[]]]#список жанров
        file = open('C:\\Users\\alexa\\Documents\\Films.txt', 'r',encoding = 'UTF-8')
        for line in file:#добавление фильмов в список жанров
            A = line.split(', ')
            for j in range(len(l)):
                if A[2]==l[j][0]:
                    l[j][1].append(A)

        diclist = []
        for k in range(first,second+1):
            diclist.append(k)
        dic =dict.fromkeys(diclist[:])#создание словаря годов
        for k in range(first,second+1):#добавление информации в словарь
            d = []
            for j in range(len(l)):
                if(l[j][1]!=[]):
                    for q in range((len(l[j][1]))):
                        if int(l[j][1][q][1])==k:
                            d.append((l[j][1][q]))
            dic.update({int(k):d})
        for el in dic.items():#добавление элементов словаря в бинарное дерево
            T[el[0]] = el
        for que in range(first,second+1):#поиск в бинарном дереве нужного года и жанра
            if T[que][1] is not None :
                for t in range(len(T[que][1])):
                    if str(T[que][1][t][2])==self.ui.Type3.currentText():
                        self.ui.listFilms.addItem("Название: " + str(T[que][1][t][0])+", Жанр: "
                                                  +str(T[que][1][t][2])+", Год выпуска: "
                                                  +str(T[que][1][t][1])+", Режиссёр: "
                                                  +str(T[que][1][t][3]))
                    elif str(self.ui.Type3.currentText()) == "любой":
                        self.ui.listFilms.addItem("Название: " + str(T[que][1][t][0])+", Жанр: "
                                                  +str(T[que][1][t][2])+", Год выпуска: "
                                                  +str(T[que][1][t][1])+", Режиссёр: "+str(T[que][1][t][3]))
Exemplo n.º 3
0
def preOrderTraversal(root):
    if root is None:
        return None

    result = []
    stack = [root]

    while stack:
        currNode = stack.pop()
        result.append(currNode.value)

        if currNode.right:
            stack.append(currNode.right)

        if currNode.left:
            stack.append(currNode.left)

    return result


BST = BinarySearchTree(6)
BST.insert(4)
BST.insert(9)
BST.insert(5)
BST.insert(2)
BST.insert(8)
BST.insert(12)

result = preOrderTraversal(BST.root)

print(result)
Exemplo n.º 4
0
from Tree import BinarySearchTree
from P4_3 import miniHeightBST


def createLevelLinkedList(root, lists, level):

    if root == None:
        return None
    if len(lists) == level:
        linkedlist = []
        lists.append(linkedlist)
    else:
        linkedlist = lists[level]
    linkedlist.append(root.key)
    createLevelLinkedList(root.leftChild, lists, level + 1)
    createLevelLinkedList(root.rightChild, lists, level + 1)
    return lists


T4 = BinarySearchTree()
i = [1, 2, 3, 4, 5, 6]
T4.root = miniHeightBST(i, 0, len(i) - 1)

T4.root.printSubtree(5)
lists = []
result = createLevelLinkedList(T4.root, lists, 0)

for i in result:
    print i
Exemplo n.º 5
0
    return subTree(T1.leftChild, T2) or subTree(T1.rightChild, T2)


def Check(T1, T2):
    if T1 == None and T2 == None:
        return True
    if T1 == None or T2 == None:
        return False
    if T1.key != T2.key:
        return False
    return Check(T1.leftChild, T2.leftChild) and Check(T1.rightChild, T2.rightChild)


# Testing part...

T8_0 = BinarySearchTree()
T8_1 = BinarySearchTree()
T8_2 = BinarySearchTree()

print "Tree 0:"
list0 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
T8_0.root = miniHeightBST(list0, 0, len(list0) - 1)
T8_0.root.printSubtree(5)

list1 = [2, 1, 3, 4]
for i in list1:
    T8_1.insertion(i)
print "Tree 1: "
T8_1.root.printSubtree(5)

print "Tree 2:"
Exemplo n.º 6
0
    u = len(s)
    first_line = (x + 1) * ' ' + (n - x - 1) * \
        '_' + s + y * '_' + (m - y) * ' '
    second_line = x * ' ' + '/' + \
        (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' '
    if p < q:
        left += [n * ' '] * (q - p)
    elif q < p:
        right += [m * ' '] * (p - q)
    zipped_lines = zip(left, right)
    lines = [first_line, second_line] + \
        [a + u * ' ' + b for a, b in zipped_lines]
    return lines, n + m + u, max(p, q) + 2, n + u // 2


BST = BinarySearchTree(6)
BST.insert(3)
BST.insert(2)
BST.insert(4)
BST.insert(-1)
BST.insert(1)
BST.insert(-2)
BST.insert(8)
BST.insert(7)

print("before deletion:")
display(BST.root)

BST.delete(6)
print("after deletion:")
display(BST.root)
Exemplo n.º 7
0
 def __init__(self, distributorName):
     self.distributorName = distributorName
     self.includes = BinarySearchTree()
     self.excludes = [BinarySearchTree()]
    while(buffer.isEmpty() is False):
        node = buffer.peek()
        if(node.rightChild != None and node.rightChild.visited is False): # We have to set a visited flag that make the
            node = node.rightChild                                        # nodes will not visit multiple times.
            while(node != None):
                buffer.push(node)
                parent = node
                node = node.leftChild

            if(parent.rightChild == None):
                arraylist.append(parent.key)
                parent.visited = True
                buffer.pop()
        else:
            node.visited = True                                          # Set visited flags
            arraylist.append(node.key)
            buffer.pop()
    return arraylist

#Testing part...
TreeRoot = BinarySearchTree()
Treelist = [10,5,3,4,7,6,8,11,12,9]

for i in Treelist:
    TreeRoot.insertion(i)

TreeRoot.root.printSubtree(5)

result = postOrderTraversial(TreeRoot.root)
print result
Exemplo n.º 9
0
    node = root
#    stack.push(node)
    while(stack.isEmpty() is False or node != None):
        if(node != None):
            stack.push(node)
            node = node.leftChild
        else:
            node = stack.pop()
            list.append(node.key)
            node = node.rightChild
    print list
    return checkOrder(list)


def checkOrder(list):
    while(len(list) != 1):
        buffer = list.pop()
        if(buffer < max(list)):
            return False
    return True




T5 = BinarySearchTree();
list = [1,2,3,4,5]
T5.root = miniHeightBST(list,0,len(list) - 1)
T5.root.printSubtree(5)


print (checkBST(T5.root) and "True") or "False"
Exemplo n.º 10
0
from Tree import BinarySearchTree

my_tree = BinarySearchTree()

my_tree.insert(100)
my_tree.insert(200)
my_tree.insert(50)
my_tree.insert(75)
my_tree.insert(150)

my_tree.inorder(my_tree.root)
Exemplo n.º 11
0
    difference = abs((leftHeight-rightHeight))
    if(difference > 1):
        return -1
    else:
        return max(leftHeight,rightHeight) + 1


def checkBalance(root):
    if(checkHeight(root) == -1):
        print "The tree is not balanced!"

    else:
        print "The height of tree is: " + str(checkHeight(root))

# Testing Part...
balance = [5,3,2,4,6]
unbalance = [5,3,2,4,6,1]

T1 = BinarySearchTree()
T2 = BinarySearchTree()
for i in balance:
    T1.insertion(i)
T1.root.printSubtree(5)
for i in unbalance:
    T2.insertion(i)
T2.root.printSubtree(5)

checkBalance(T1.root)
checkBalance(T2.root)
Exemplo n.º 12
0
    if(node.rightChild != None):
        node = node.rightChild
        while(node.leftChild != None):
            node = node.leftChild

        return node
    else:
        current = node
        parent = node.parent
        while(parent != None and parent.leftChild != current):
            current = parent
            parent = current.parent

        return parent

# Testing Part...

T6 = BinarySearchTree()
Treelist = [10,5,3,4,7,6,8,11]

for i in Treelist:
    T6.insertion(i)


T6.root.printSubtree(5)
print "The in order successor of node 7 should be 8: " + \
      str(findInorderSuccessor(T6.root.leftChild.rightChild).key)
print "The in order successor of node 4 should be 5: " + \
      str(findInorderSuccessor(T6.root.leftChild.leftChild.rightChild).key)