Пример #1
0
 def air_neighbours_available(self):
     '''Returns a list with neighbours with open airport'''
     a_n_a = LinkedList()
     for neib in self.air_neighbours:
         if self.open_airport and neib.open_airport:
             a_n_a.append(neib)
     return a_n_a
Пример #2
0
class LinkedListTest(unittest.TestCase):
    def setUp(self) -> None:
        self.linkedlist = LinkedList()
        node1 = Node()
        node2 = Node()
        node1.next = node2
        node3 = Node()
        node2.next = node3
        self.linkedlist.head = node1

    def tearDowm(self) -> None:
        pass

    def test_linkedlist_length(self):
        self.assertEqual(3, self.linkedlist.len())

    def test_insert_at_begining(self):
        node_begining = Node
        self.linkedlist.insert_at_begining(node_begining)
        self.assertEqual(4, self.linkedlist.len())

    def test_insert_at_end(self):
        node_end = Node()
        self.linkedlist.insert_at_end(node_end)
        self.assertEqual(4, self.linkedlist.len())

    def test_insert_at_position(self):
        node_pos = Node()
        self.linkedlist.insert_at_position(0, node_pos)
        self.assertEqual(4, self.linkedlist.len())
Пример #3
0
 def neighbours_available(self):
     '''Returns list with neighbours with opened fronteir'''
     n_a = LinkedList()
     for neib in self.neighbours:
         if self.open_fronteir and neib.open_fronteir:
             n_a.append(neib)
     return n_a
Пример #4
0
    def test_insert_illegal_type_raises_ValueError(self):
        # Arrange
        l = LinkedList(1)

        # Act + Assert
        with self.assertRaises(ValueError):
            l.insert('2')
Пример #5
0
    def test_delete_list_item_that_doesnt_exist_raise_value_error(self):
        # Arrange
        l = _factory([1,2,3,4,5])

        # Act + Assert
        with self.assertRaises(ValueError):
            LinkedList.delete_list(l, 6)
Пример #6
0
class LinkedListQueue(QueueABC):
    """
    Implementation of the queue data structure
    using a linked list for FIFO operations
    """
    def __init__(self):
        self._list = LinkedList()

    def first(self):
        """
        Examine and return the element at the front of the queue
        :return: first element
        :raise: QueueException if empty queue
        """
        # if there is nothing in the queue then raise an exception
        if self.is_empty():
            raise QueueException("Cannot fetch first from empty queue")
        return self._list.first.element

    def enqueue(self, x):
        """
        Add an element to the back of the queue.
        :param x: object to add
        :return:
        :raise: TypeError if nothing is queued
        """
        self._list.insert_last(x)

    def __len__(self):
        """
        Return the length of the queue
        :return: number of elements
        """
        return len(self._list)

    def size(self):
        """
        Return the number of elements in the queue
        :return: number of elements
        """
        return len(self._list)

    def dequeue(self):
        """
        Remove and return the first element in the queue
        :return: first element
        """
        # if there is nothing in the queue then raise an exception
        if self.is_empty():
            raise QueueException("Cannot dequeue from empty queue")

        return self._list.delete_first()

    def is_empty(self):
        """
        Return true if queue is empty else False
        :return: True or False
        """
        return True if len(self._list) == 0 else False
Пример #7
0
 def setUp(self) -> None:
     self.linkedlist = LinkedList()
     node1 = Node()
     node2 = Node()
     node1.next = node2
     node3 = Node()
     node2.next = node3
     self.linkedlist.head = node1
Пример #8
0
    def test_delete_list_item(self):
        # Arrange
        l = _factory([1,2,3,4,5])

        # Act
        LinkedList.delete_list(l, 3)

        # Assert
        self.assertEqual(_factory([1,2,4,5]), l)
Пример #9
0
class LinkedListStack(StackABC):
    """
    Implementation of the stack data structure
    using a linked list for LIFO operations
    """
    def __init__(self):
        self._list = LinkedList()

    def __len__(self):
        return self.size()

    def __iter__(self):
        for i in self._list:
            yield i

    def size(self):
        """
        Return number of items in stack
        """
        return len(self._list)

    def peek(self):
        """
        Return the obj, but leave it on the stack
        :return: object
        :raise: StackException
        """
        if self._list.first:
            return self._list.first.element
        else:
            raise StackException("Cannot peek into empty stack")

    def push(self, x):
        """
        Add element x to top of stack
        :param x: object to push on stack
        :return:
        """
        self._list.insert_first(x)

    def is_empty(self):
        """
        Return True if empty stack else False
        :return: True/False
        """
        return False if len(self._list) else True

    def pop(self):
        """
        Remove element from top of stack and return it
        :return: newest object
        :raise: StackException
        """
        if len(self._list):
            return self._list.delete_first()
        else:
            raise StackException("Cannot pop from empty stack")
Пример #10
0
def union(llist_1, llist_2):
    llst = LinkedList()

    lst_1 = llist_1.to_list()
    lst_2 = llist_2.to_list()
    nodes = set(lst_1 + lst_2)

    for node in nodes:
        llst.append(node)

    return llst
Пример #11
0
def intersection(llist_1, llist_2):
    llst = LinkedList()

    lst_1 = llist_1.to_list()
    lst_2 = llist_2.to_list()
    nodes = set(lst_1).intersection(set(lst_2))

    for node in nodes:
        llst.append(node)

    return llst
Пример #12
0
    def test_add_to_list(self):
        name = "Jose"
        matric = "1234"
        year = 2

        node = Node(name, matric, year)

        linked_list = LinkedList()

        linked_list.add_to_list(node)

        self.assertEqual(linked_list.get_root(), node)
Пример #13
0
    def test_insert(self):
        # Arrange
        l = LinkedList(1)

        # Act
        l.insert(2)
        l.insert(3)

        # Assert
        self.assertEqual(1, l.item)
        self.assertEqual(2, l.next_l.item)
        self.assertEqual(3, l.next_l.next_l.item)
        self.assertEqual(None, l.next_l.next_l.next_l)
Пример #14
0
    def test_add_many_to_list(self):
        names = ("Jose", "1234", 2), ("Rolf", "2345", 3), ("Anna", "3456", 7)

        nodes = [Node(name, matric, year) for name, matric, year in names]

        linked_list = LinkedList()

        for node in nodes:
            linked_list.add_to_list(node)

        marker = linked_list.get_root()
        for i in range(len(nodes) - 1, -1, -1):
            self.assertEqual(marker, nodes[i])
            marker = marker.get_next()
Пример #15
0
def pl_true(formula, model):
    # zavisi na resenem problemu
    if formula == "kb":
        return model == LinkedList([("p3", True), ("p2", True), ("p1", True)]) or \
               model == LinkedList([("p3", True), ("p2", True), ("p1", False)])
    if formula == "alpha":
        return model == LinkedList([("p3", True), ("p2", True), ("p1", True)]) or \
               model == LinkedList([("p3", False), ("p2", True), ("p1", True)]) or \
               model == LinkedList([("p3", True), ("p2", True), ("p1", False)]) or \
               model == LinkedList([("p3", False), ("p2", True), ("p1", False)])
    if formula == "beta":
        return model == LinkedList([("p3", True), ("p2", True), ("p1", True)]) or \
               model == LinkedList([("p3", True), ("p2", False), ("p1", True)]) or \
               model == LinkedList([("p3", False), ("p2", True), ("p1", True)]) or \
               model == LinkedList([("p3", False), ("p2", False), ("p1", True)])
Пример #16
0
def get_llst(lst1, lst2):
    llst1 = LinkedList()
    llst2 = LinkedList()
    for value in lst1:
        llst1.append(value)
    for value in lst2:
        llst2.append(value)
    return llst1, llst2
Пример #17
0
def andor(start):
    heap = [(0, 0, LinkedList([(0, 0, 0, start, Nil)]), Nil)]
    while True:
        try:
            f, g, nodes, solved = heapq.heappop(heap)
        except IndexError:  # fronta je prazdna
            raise ValueError("Reseni neexistuje.")
        if nodes == Nil:  # seznam uzlu k vyreseni je prazdny
            return reconstruct_search_tree(solved)
        _, g1, c, node, path = nodes.head
        if is_goal(node):
            solved = Cons((node, Cons(node, path)), solved)
            heapq.heappush(heap, (f - h(node) - c, g - c, nodes.tail, solved))
        elif f <= biggest:
            succ = get_successors(node)
            if succ is None:  # narazili jsme na necilovy uzel
                continue
            op, successors = succ
            path1 = Cons(node, path)
            if op == "and":
                nodes1 = nodes.tail
                for m, c in successors:
                    if not member(m, path1):
                        nodes1 = insert((g1 + c + h(m), g1 + c, c, m, path1),
                                        nodes1)
                        f = g + c + h(m)
                        g = g + c
                heapq.heappush(heap, (f, g, nodes1, solved))
            if op == "or":
                for m, c in successors:
                    if not member(m, path1):
                        nodes1 = insert((g1 + c + h(m), g1 + c, c, m, path1),
                                        nodes.tail)
                        heapq.heappush(heap,
                                       (g + c + h(m), g + c, nodes1, solved))
Пример #18
0
def partition(linked_list, x):
    first_low = first_high = low_tail = high_tail = None
    node = linked_list.head

    while node != None:
        next = node.next
        node.next = None

        if node.data < x:
            if low_tail:
                low_tail.next = node
            else:
                first_low = node

            low_tail = node
        else:
            if high_tail:
                high_tail.next = node
            else:
                first_high = node

            high_tail = node

        node = next

    low_tail.next = first_high
    return LinkedList(first_low)
Пример #19
0
 def push(self, item):
     if self._head_of_queue is None:
         self._ll = LinkedList(item)
         self._head_of_queue = self._ll
     else:
         self._head_of_queue.insert(item)
         self._head_of_queue = self._head_of_queue.next_l
Пример #20
0
def insert(node, nodes):
    if nodes == Nil:
        return LinkedList([node])
    f = node[0]
    f1 = nodes.head[0]
    if f <= f1:
        return Cons(node, nodes)
    return Cons(nodes.head, insert(node, nodes.tail))
Пример #21
0
 def __init__(self, name, initial_population):
     self.name = name
     self.initial_population = initial_population
     self.healthy_total = initial_population
     self.dead_total = 0
     self.infected_total = 0
     self.actions_queue = LinkedList()
     self.neighbours = LinkedList()
     self.neighbours_names = LinkedList()
     self.air_neighbours = LinkedList()
     self.air_neighbours_names = LinkedList()
     self.open_airport = True
     self.open_fronteir = True
     self.has_cure = False
     self.has_mask = False
     self.infected_this_day = 0
     self.dead_this_day = 0
Пример #22
0
def queens(n):
    problem = Problem()
    domain = range(n + 1)[1:]
    variables = LinkedList(list("X%d" % i for i in range(n + 1)[1:]))
    for name in variables:
        problem.addVariable(name, domain)
    constr_all(problem, variables)
    return problem
def hanoi(n, a, b, c):
    if n == 1:
        return LinkedList(["%s to %s" % (a, b)])
    if n < 1:
        raise ValueError("n musi byt kladne")
    if (n+1, a, c, b) not in hanoi_mem:
        hanoi_mem[(n-1, a, c, b)] = hanoi(n-1, a, c, b)
    if (n+1, a, c, b) not in hanoi_mem:
        hanoi_mem[(n-1, c, b, a)] = hanoi(n-1, c, b, a)
    ms1 = hanoi_mem[(n-1, a, c, b)]
    ms2 = hanoi_mem[(n-1, c, b, a)]
    return append(ms1, Cons("%s to %s" % (a, b), ms2))
Пример #24
0
class Queue(object):
    @staticmethod
    def from_list(l):
        _q = Queue()
        for item in l:
            _q.insert(item)
        return _q

    def __init__(self, max_size=None):
        self._ll = None
        self._head_of_queue = None
        self.max_size = max_size

    def push(self, item):
        if self._head_of_queue is None:
            self._ll = LinkedList(item)
            self._head_of_queue = self._ll
        else:
            self._head_of_queue.insert(item)
            self._head_of_queue = self._head_of_queue.next_l

    def to_list(self):
        return self._ll.to_list() if self._ll is not None else []

    def pop(self):
        if len(self) == 0:
            raise ValueError("Can't pop from an empty queue")

        ans = self._ll.item
        self._ll = self._ll.next_l
        if self._ll is None:
            self._head_of_queue = None
        return ans

    def __len__(self):
        return 0 if self._ll is None else len(self._ll)

    def __eq__(self, other):
        return self._ll == other._ll

    def __ne__(self, other):
        return not self.__eq__(other)

    def __iter__(self):
        return iter(self.to_list())

    def __str__(self):
        return '->'.join(map(str, self.to_list()[::-1]))
def get_successors(node):
    if node[0] == "direct":
        _, x, z = node
        succ = Nil
        if x in stateS and z in stateU:
            for y in borders:
                succ = Cons((("via", x, z, y), 0), succ)
        if x in distances:
            for y, d in distances[x]:
                succ = Cons((("direct", y, z), d), succ)
        if succ == Nil:
            return None
        return ("or", succ)
    if node[0] == "via":
        _, x, z, y = node
        return ("and", LinkedList([(("direct", x, y), 0), (("direct", y, z), 0)]))
Пример #26
0
def reconstruct_search_tree(leaves):
    tree = dict()
    for node, path in leaves:
        tree[node] = "goal"
        while path != Nil and path.tail != Nil:
            node = path.head
            parent = path.tail.head
            if parent not in tree:
                op, _ = get_successors(parent)
                tree[parent] = (op + "_result", LinkedList([node]))
            else:
                op, nodes = tree[parent]
                if not member(node, nodes):
                    tree[parent] = (op, Cons(node, nodes))
                break
            path = path.tail
    return tree
Пример #27
0
 def __init__(self, file_population, file_borders, file_airports,
              file_ramdom_airports):
     self.file_population = file_population
     self.file_borders = file_borders
     self.file_airports = file_airports
     self.file_ramdom_airports = file_ramdom_airports
     self.countries = LinkedList()
     self.names = LinkedList()
     self.cure_progress = 0.0
     self.cure_delivered = False
     self.infection_detected = False
     self.infection_detection_day = 0
     self.actions_queue = LinkedQueue()
     self.infection = None
     self.day = 0
     self.closed_airports_today = ""
     self.closed_fronteirs_today = ""
     self.gave_masks_today = ""
     # sum of the new infected every day
     # It does not include the healing process
     self.infected_to_this_day = 0
     self.infected_per_day_list = LinkedList(1)
     self.dead_per_day_list = LinkedList(0)
 def linkedlist(self, e1, e2, e3):
     linkedlist = LinkedList(e1)
     linkedlist.append(e2)
     linkedlist.append(e3)
     return linkedlist
#!/usr/bin/env python
# encoding=utf-8 (pep 0263)

from linked_lists import LinkedList, Cons, Nil
from best_search import BestSearch

biggest = 99
start = LinkedList([(2, 2), (3, 1), (2, 3), (2, 1), (3, 3), (1, 2), (3, 2),
                    (1, 3), (1, 1)])
goal = LinkedList([(1, 3), (2, 3), (3, 3), (1, 2), (2, 2), (3, 2), (1, 1),
                   (2, 1), (3, 1)])


def is_goal(state):
    return state == goal


def move_anyYC(numbers):
    if numbers == Nil:
        return
    xb, yb = numbers.head
    if xb > 1:  # pohyb mezery doleva
        xl = xb - 1
        new_tail = replace((xl, yb), (xb, yb), numbers.tail)
        yield (Cons((xl, yb), new_tail), 1)
    if xb < 3:  # pohyb mezery doprava
        xr = xb + 1
        new_tail = replace((xr, yb), (xb, yb), numbers.tail)
        yield (Cons((xr, yb), new_tail), 1)
    if yb > 1:  # pohyb mezery dolu
        yd = yb - 1
Пример #30
0

def member(x, xs):
    if xs == Nil:
        return False
    if x == xs.head:
        return True
    return member(x, xs.tail)


def h(_):
    # zavisi na resenem problemu
    return 0


graph = dict(a=("or", LinkedList([("b", 1), ("c", 3)])),
             b=("and", LinkedList([("d", 1), ("e", 1)])),
             c=("and", LinkedList([("f", 2), ("g", 1)])),
             e=("or", LinkedList([("h", 6)])),
             f=("or", LinkedList([("h", 2), ("i", 3)])))

goals = dict(d=True, g=True, h=True)


def is_goal(node):
    # zavisi na resenem problemu
    return node in goals


# tato funkce nahrazuje prologovska fakta tvaru node ---> Op:Subtrees
# a pro zadany node navraci prislusne Op:Subtrees
def path(a, z, graph):
    for cesta in path1(a, LinkedList([z]), graph, 1):
        yield cesta
    for a, b in member_anyX(edges):
        if y == a:
            yield b
        if y == b:
            yield a


def member(x, xs):
    if xs == Nil:
        return False
    if x == xs.head:
        return True
    return member(x, xs.tail)


def member_anyX(xs):
    if xs == Nil:
        return
    yield xs.head
    for x in member_anyX(xs.tail):
        yield x


_graph = (LinkedList(["a", "b", "c", "d"]),
          LinkedList([("a", "b"), ("b", "d"), ("b", "c"), ("c", "d")]))

# demonstracni vypis
if __name__ == "__main__":
    print('Cesta v grafu\n')
    print('next(path("a", "c", _graph)) : %s' % next(path("a", "c", _graph)))
Пример #33
0
#!/usr/bin/env python
# encoding=utf-8 (pep 0263)

from __future__ import division
from linked_lists import LinkedList, Cons, Nil
from best_search import BestSearch

biggest = 99
start = (LinkedList([("t1", 4), ("t2", 2), ("t3", 2), ("t4", 20), ("t5", 20),
                     ("t6", 11), ("t7", 11)]),
         LinkedList([("idle", 0), ("idle", 0), ("idle", 0)]), 0)

precedence = dict(t1=["t4", "t5"], t2=["t4", "t5"], t3=["t5", "t6", "t7"])


def goes_before(T1, T2):
    if T1 in precedence:
        if T2 in precedence[T1]:
            return True
        for T in precedence[T1]:
            if goes_before(T, T2):
                return True
    return False


def is_goal(state):
    # zavisi na resenem problemu
    waiting, _, _ = state
    return waiting == Nil

Пример #34
0
def _factory(l):
    _l = LinkedList(l[0])
    for item in l[1:]:
        _l.insert(item)
    return _l
Пример #35
0
 def setUp(self):
     self.link_list = LinkedList()
     self.double_link_list = DoubleLinkList()
    pos1 = poslist.head
    if poslist.tail == Nil:
        return minimax(pos1)
    _, val1 = minimax(pos1)
    pos2, val2 = best(poslist.tail)
    return better_of(pos1, val1, pos2, val2)


def better_of(pos0, val0, pos1, val1):
    if min_to_move(pos0) and val0 > val1 or max_to_move(pos0) and val0 < val1:
        return (pos0, val0)
    return (pos1, val1)


start = "root"
graph = dict(root=("max", LinkedList(["a1", "a2", "a3"])),
             a1=("min", LinkedList(["b1", "b2", "b3"])),
             a2=("min", LinkedList(["c1", "c2", "c3"])),
             a3=("min", LinkedList(["d1", "d2", "d3"])),
             b1=("max", Nil),
             b2=("max", Nil),
             b3=("max", Nil),
             c1=("max", Nil),
             c2=("max", Nil),
             c3=("max", Nil),
             d1=("max", Nil),
             d2=("max", Nil),
             d3=("max", Nil))


def moves(pos):
Пример #37
0
#!/usr/bin/env python
# encoding=utf-8 (pep 0263)

from linked_lists import LinkedList, Cons, Nil

graph = dict(
    a=("or", LinkedList(["b", "c"])),
    b=("and", LinkedList(["d", "e"])),
    c=("and", LinkedList(["f", "g"])),
    e=("or", LinkedList(["h"])),
    f=("and", LinkedList(["h", "i"])))

goals = dict(d=True, g=True, h=True)

def is_goal(node):
    # zavisi na resenem problemu
    return node in goals

def solve(node):
    if is_goal(node):
        yield node
    if node in graph:
        nodes = graph[node][1]
        if graph[node][0] == "or":
            for node1 in member_anyX(nodes):
                for tree in solve(node1):
                    yield (node, "--->", tree)
        elif graph[node][0] == "and":
            for trees in solveall(nodes):
                yield (node, "--->", ("and", trees))