Пример #1
0
 def push(self, data):
     node = Node(data)
     if self.isEmpty():
         self.top = node
         return
     node.next = self.top
     self.top = node
Пример #2
0
 def insert(self, index, data):
     node = Node(data=data)
     cur_node = self.head
     cur_index = 0
     while cur_index < index - 1 and cur_node is not None:  #O(n)
         cur_node = cur_node.next
         cur_index += 1
     node.next = cur_node.next
     cur_node.next = node
Пример #3
0
 def insert(self,value):
     self.size += 1
     position = self.table_position(value)
     obj_node = Node(value)
     if(self.table[position] == None):
         self.table[position] = obj_node
     else:
         obj_node.next_node = self.table[position]
         self.table[position] = obj_node
Пример #4
0
 def show_cursor_coordinate(self, event):
     "Display current cursor coordinate on top-right corner"
     self.delete('coordinate')
     x = round(event.x - self.width / 2)
     y = round(self.height / 2 - event.y)
     self.create_text(60, 20, text='x=%d, y=%d' % (x, y), tag='coordinate')
     if Node.find_node(x, y) >= 0:
         self.create_text(60,
                          40,
                          text='Node %d' % Node.find_node(x, y),
                          tag='coordinate')
Пример #5
0
 def prepend(self, data):
     node = Node(data=data)
     if self.head is None:
         self.head = node
         self.head.next = None
     if self.tail is None:
         self.tail = node
         self.tail.next = None
     else:
         node.next = self.head
         self.head = node
Пример #6
0
def testRandomMaze():
    import random
    import matplotlib.pyplot as plt
    import time

    start_time = time.time()

    maze = Maze()
    plt.plot(0, 0, 'go')
    for i in range(10):
        x = random.randrange(0, 100)
        y = random.randrange(0, 100)
        plt.plot(x, y, 'bo')
        if Node.find_node(x, y) < 0:
            n = Node(x, y)
            r = random.choice(list(n.registry.copy()))
            n.connect_to(r)
            plt.plot([n.x, r.x], [n.y, r.y], 'r-')
            r = random.choice(list(n.registry.copy()))
            n.connect_to(r)
            plt.plot([n.x, r.x], [n.y, r.y], 'r-')
        else:
            print("Node %s already exist at (%d,%d)" %
                  (Node.registry[Node.find_node(x, y)], x, y))

    e = random.choice(Node.registry)
    maze.mark_exit(e)
    plt.plot(e.x, e.y, 'rd')

    try:
        print(maze.find_way_out())
    except NoSolution:
        print("No solution")
    print("Time spent: " + str(time.time() - start_time))
    plt.show()
Пример #7
0
 def append(self, data):
     node = Node(data=data)
     if self.head is None:
         self.head = node
         self.head.next = None
         self.head.prev = None
     if self.tail is None:
         self.tail = node
         self.tail.next = None
         self.tail.prev = None
     else:
         node.prev = self.tail.prev
         self.tail.next = node
         self.tail = node
Пример #8
0
 def append(self, data):
     node: Node = Node(data)
     if (self.head == None):
         self.head = node
         return
     current: Node = self.head
     while (current.next != None):
         current = current.next
     current.next = node
Пример #9
0
    def add(self, data):
        node = Node(data)
        # if the tail is not None add a node right next to it and update the tail (line 21-23)
        if (self.tail != None):
            self.tail.next = node
        self.tail = node

        if (self.head == None):
            self.head = node
        """ when the head is None (when the queue is empty) and a node is added to the queue,
Пример #10
0
def main():
    frontier = Frontier()
    # frontier = []
    initial_state = np.copy(scramble.x)
    initial_cost = 0
    initial_node = Node(initial_state, initial_cost, 0)

    # IDAS(initial_node, frontier)

    frontier.add(initial_node)
    expanded_set = set()

    IDFS(initial_node, frontier, 11)
Пример #11
0
        def connect_nearest_manhattan(n: Node) -> bool:
            with warnings.catch_warnings():
                warnings.filterwarnings('ignore')
                possible_y = dict_x[n.x]
                loc_y = possible_y.index(n.y)
                tc = set()  # short for to be connected

                if loc_y > 0:
                    tc.add((n.index, Node.find_node(n.x,
                                                    possible_y[loc_y - 1])))

                if loc_y < len(possible_y) - 1:
                    tc.add((n.index, Node.find_node(n.x,
                                                    possible_y[loc_y + 1])))

                possible_x = dict_y[n.y]
                loc_x = possible_x.index(n.x)

                if loc_x > 0:
                    tc.add((n.index, Node.find_node(possible_x[loc_x - 1],
                                                    n.y)))

                if loc_x < len(possible_x) - 1:
                    tc.add((n.index, Node.find_node(possible_x[loc_x + 1],
                                                    n.y)))

                for n0, n1 in sorted(tc, key=sort_key):
                    n0 = Node.registry[n0]
                    n1 = Node.registry[n1]

                    if self.connect(n0.index,
                                    n1.index,
                                    show_distance=show_distance,
                                    update=update):
                        return True

                return False
Пример #12
0
def RIGHT(stateNode):
    state2 = stateNode.state[:]
    space = state2.index(0)
    if space != 2 and space != 5 and space != 8:
        temp = state2[space + 1]
        state2[space] = temp
        state2[space + 1] = 0
        leafNode = Node(' ')
        leafNode.state = state2
        leafNode.parent = stateNode
        leafNode.move = "Right"
        leafNode.distance = -1
        return leafNode
    else:
        return False
Пример #13
0
def LEFT(stateNode):
    state2 = stateNode.state[:]
    space = state2.index(0)
    if space != 0 and space != 3 and space != 6:
        temp = state2[space - 1]
        state2[space] = temp
        state2[space - 1] = 0
        leafNode = Node(' ')
        leafNode.state = state2
        leafNode.parent = stateNode
        leafNode.move = "Left"
        leafNode.distance = -1
        return leafNode
    else:
        return False
Пример #14
0
def UP(stateNode):
    state2 = stateNode.state[:]
    space = state2.index(0)
    if space > 2 and space < 9:
        temp = state2[space - 3]
        state2[space] = temp
        state2[space - 3] = 0
        leafNode = Node(' ')
        leafNode.state = state2
        leafNode.parent = stateNode
        leafNode.move = "Up"
        leafNode.distance = -1
        return leafNode
    else:
        return False
Пример #15
0
def DOWN(stateNode):
    state2 = stateNode.state[:]
    space = state2.index(0)
    if space > -1 and space < 6:
        temp = state2[space + 3]
        state2[space] = temp
        state2[space + 3] = 0
        leafNode = Node(' ')
        leafNode.state = state2
        leafNode.parent = stateNode
        leafNode.move = "Down"
        leafNode.distance = -1
        return leafNode
    else:
        return False
Пример #16
0
    def generate_maze(self,
                      n,
                      s=10,
                      c=0.55,
                      show_distance=True,
                      update=True,
                      show_node_num=True):
        """
        :param n: number of nodes to be generated
        :param s: size of the maze. The function will run infinitely if n>s**2
        :param c: chance of two nodes connecting each other when they don't have to
        :param update: Update canvas after each drawing
        :param show_distance: show distance on the coordinate plane between two connected nodes
        :return: None
        This function generate a maze on the coordinate plane so that
        1. there is no isolated nodes
        2. there is no diagonal connection between nodes
        3. there is no overlapping edges
        """
        _n = n
        size = s

        zoom = (
            self.coordinate_plane.height - 20
        ) // size  # scale the maze to be size*size, height should be the same as min(height,width)

        for i in range(n):  # add n of nodes to the map
            flag = False
            while not flag:
                x = random.randrange(0, size) - size // 2
                y = random.randrange(0, size) - size // 2
                if Node.find_node(x * zoom, y * zoom) < 0:
                    flag = True
                    self.add_node(x * zoom,
                                  y * zoom,
                                  update=update,
                                  show_number=show_node_num)

        # The part below is super inefficient and badly written but I DON'T CARE

        dict_x = {}  # stored value will be x:y
        dict_y = {}  # stored value will be y:x

        for x, y in Node.map_origin.keys():
            try:
                dict_x[x].append(y)
                dict_x[x].sort()
            except KeyError:
                dict_x[x] = [y]

            try:
                dict_y[y].append(x)
                dict_y[y].sort()
            except KeyError:
                dict_y[y] = [x]

        to_be_connected = set(
        )  # in a tuple (n0,n1) where n0 and n1 are index number of a node
        nodes_with_edge = set()

        for x in dict_x:
            i = 0
            while i < len(dict_x[x]) - 1:
                y0 = dict_x[x][i]
                y1 = dict_x[x][i + 1]
                if (not Node.find_node(x, y0) in nodes_with_edge
                        and not Node.find_node(x, y1) in nodes_with_edge
                    ) or random.random(
                    ) <= c:  # to ensure each node has at least one edge
                    n0 = Node.find_node(x, y0)
                    n1 = Node.find_node(x, y1)
                    to_be_connected.add((n0, n1))
                    nodes_with_edge.add(n0)
                    nodes_with_edge.add(n1)
                i += 1

        for y in dict_y:
            i = 0
            while i < len(dict_y[y]) - 1:
                x0 = dict_y[y][i]
                x1 = dict_y[y][i + 1]
                if (not Node.find_node(x0, y) in nodes_with_edge
                        and not Node.find_node(x1, y) in nodes_with_edge
                    ) or random.random(
                    ) <= c:  # to ensure each node has at least one edge
                    n0 = Node.find_node(x0, y)
                    n1 = Node.find_node(x1, y)
                    to_be_connected.add((n0, n1))
                    nodes_with_edge.add(n0)
                    nodes_with_edge.add(n1)
                i += 1

        # Try to find intersections in the maze that is not a node

        hlines = {}  # in format y:(x0,x1) where x0<x1
        vlines = {}

        for n0, n1 in to_be_connected:
            n0 = Node.registry[n0]
            n1 = Node.registry[n1]
            if n0.x == n1.x:  # this is a vertical line
                try:
                    vlines[n0.x].append((n0.y,
                                         n1.y) if n0.y < n1.y else (n1.y,
                                                                    n0.y))
                except KeyError:
                    vlines[n0.x] = [(n0.y, n1.y) if n0.y < n1.y else
                                    (n1.y, n0.y)]
            else:  # horizontal
                try:
                    hlines[n0.y].append((n0.x,
                                         n1.x) if n0.x < n1.x else (n1.x,
                                                                    n0.x))
                except KeyError:
                    hlines[n0.y] = [(n0.x, n1.x) if n0.x < n1.x else
                                    (n1.x, n0.x)]

        for x in vlines:
            for v in vlines[x]:
                y0, y1 = v  # y0<y1
                for y in hlines:
                    if y0 <= y <= y1:
                        for h in hlines[y]:
                            x0, x1 = h
                            if x0 <= x <= x1:  # this two lines intersect at (x,y)
                                if Node.find_node(x, y) < 0:
                                    n = self.add_node(
                                        x,
                                        y,
                                        update=update,
                                        show_number=show_node_num)
                                    to_be_connected.add(
                                        (n.index, Node.find_node(x, y0)))
                                    to_be_connected.add(
                                        (n.index, Node.find_node(x, y1)))
                                    to_be_connected.add(
                                        (n.index, Node.find_node(x0, y)))
                                    to_be_connected.add(
                                        (n.index, Node.find_node(x1, y)))

        dict_x = {}
        dict_y = {}

        for x, y in Node.map_origin.keys():
            try:
                dict_x[x].append(y)
                dict_x[x].sort()
            except KeyError:
                dict_x[x] = [y]

            try:
                dict_y[y].append(x)
                dict_y[y].sort()
            except KeyError:
                dict_y[y] = [x]

        def sort_key(t):  # sort the edges by length
            n0 = Node.registry[t[0]]
            n1 = Node.registry[t[1]]
            return self.calculate_distance(n0.x, n0.y, n1.x, n1.y)

        with warnings.catch_warnings():
            warnings.filterwarnings('ignore')
            for n0, n1 in sorted(to_be_connected, key=sort_key):
                self.connect(n0,
                             n1,
                             show_distance=show_distance,
                             update=update)

        def connect_nearest_manhattan(n: Node) -> bool:
            with warnings.catch_warnings():
                warnings.filterwarnings('ignore')
                possible_y = dict_x[n.x]
                loc_y = possible_y.index(n.y)
                tc = set()  # short for to be connected

                if loc_y > 0:
                    tc.add((n.index, Node.find_node(n.x,
                                                    possible_y[loc_y - 1])))

                if loc_y < len(possible_y) - 1:
                    tc.add((n.index, Node.find_node(n.x,
                                                    possible_y[loc_y + 1])))

                possible_x = dict_y[n.y]
                loc_x = possible_x.index(n.x)

                if loc_x > 0:
                    tc.add((n.index, Node.find_node(possible_x[loc_x - 1],
                                                    n.y)))

                if loc_x < len(possible_x) - 1:
                    tc.add((n.index, Node.find_node(possible_x[loc_x + 1],
                                                    n.y)))

                for n0, n1 in sorted(tc, key=sort_key):
                    n0 = Node.registry[n0]
                    n1 = Node.registry[n1]

                    if self.connect(n0.index,
                                    n1.index,
                                    show_distance=show_distance,
                                    update=update):
                        return True

                return False

        def connect_nearest(n: Node) -> bool:
            with warnings.catch_warnings():
                warnings.filterwarnings('ignore')

                for n0, n1 in sorted(zip(itertools.repeat(n), Node.registry),
                                     key=sort_key):

                    if self.connect(n0,
                                    n1,
                                    show_distance=show_distance,
                                    update=update):
                        return True

                return False

        import itertools
        for node in Node.registry.values(
        ):  # Make sure every node is connected to the main maze
            try:
                self.search_route(node, self.origin)
            except NoSolution:
                t = 0
                flag = connect_nearest_manhattan(node)
                while not flag:
                    try:
                        node = node.get_edge(
                            random.choice([k for k in node._edges.keys()])
                        ).get_other(
                            node.index
                        )  # try to connect to the main maze from its neighbours
                        flag = connect_nearest_manhattan(node)
                    except IndexError:  # An isolated node. Give up
                        print('Isolated: Giving up on node' + str(node.index))
                        break

                    t += 1
                    if t > _n:
                        print('Timeout:  Giving up on node' + str(node.index))
                        break  # attempted more than the maze size. Give up.
                else:
                    print("Succeeded: Fixed connection for node" +
                          str(node.index))
Пример #17
0
                if node.state == goal.state:
                    return (node)
                Q.queue(node)


def reConst(goal):
    node = goal
    stack = Stack()
    while node != None:
        stack.push(node)
        node = node.parent
    return stack


start = [1, 2, 3, 4, 6, 8, 7, 5, 0]
n = Node(' ')
n.state = start
n.parent = None
n.move = None
n.distance = -1

goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
p = Node(' ')
p.state = goal
p.parent = None
p.move = None
p.distance = -1

s = bfs(n, p)
print "Finished"
ss = reConst(s)
Пример #18
0
from DataStructures import Node

head = None

# Add five nodes to the beginning of the linked structure
for count in range(1, 6):
    head = Node(count, head)

# Print the contents of the structure
while head != None:
    print(head.data)
    head = head.next
        p2 = LL.head
        found_dup = False
        while p2 is not p1:
            if id(p2.data) == id(p1.data):
                print("we found the same data")
                found_dup = True
                break
        if not found_dup:
            print 'no duplicate yet', p1.data, p1.next.data
            p1 = p1.next
        else:
            print 'duplicate ', p1.data, p1.next.data
            p1 = p1.next
    LL.tail = p1


node_a = Node('data')
node_b = Node('alex')
node_c = Node('alex')
node_d = Node('hello')

node_b.next = node_c
node_c.next = node_d

linked_list = LinkedList()
linked_list.head = node_b
remove_dups_constant_space(linked_list)
print len(linked_list)
print(linked_list.head.data)
print(linked_list.head.next.data)
Пример #20
0
 def prepend(self, data):
     newHead = Node(data)
     newHead.next = self.head
     self.head = newHead
Пример #21
0
 def add_node(self, x, y, isDeadEnd=False) -> BaseNode:
     "Proxy to create a new node"
     if isDeadEnd:
         return DeadEnd(x, y)
     else:
         return Node(x, y)
Пример #22
0
def testMaze():
    maze = Maze()
    maze.create_origin()
    n0 = Node(10, 10)
    n1 = Node(10, 20)
    n2 = Node(20, 20)
    n3 = Node(20, 10)
    n4 = Node(25, 15)
    n5 = Node(30, 20)
    maze.origin.connect_to(n0)
    n0.connect_to(n1)
    n0.connect_to(n3)
    n3.connect_to(n4)
    n4.connect_to(n2)
    n1.connect_to(n2)
    n2.connect_to(n5)
    maze.mark_exit(n5)
    print(maze.find_way_out())
Пример #23
0
 def __init__(self, data):
     self.head: Node = Node(data)
Пример #24
0
 def __init__(self, data):
     self.top = Node(data)
Пример #25
0
def main():
    print("TEST")
    node: Node = Node('A')
    node.next = Node('B')
    print(str(node))
    print()

    print("BUBBLE SORT")
    arr = [10, 3, 5, 12, 20, 9]
    BubbleSort(arr)
    print(arr)
    print()

    print("MERGE SORT")
    arr2 = [45, 12, 99, 69, 1, 13]
    MergeSort(arr2)
    print(arr2)
    print()

    print("QUICK SORT")
    arr3 = [45, 12, 99, 69, 1, 13]
    QuickSort(arr3)
    print(arr3)
    print()

    print("BINARY SEARCH")
    arr4 = [1,2,6,8,14]
    #print(BinarySearchRecursive(arr4, 2, 0, len(arr) - 1))
    print(BinarySearchIterative(arr4, 8))
    print(BinarySearchRecursive(arr4, 2, 0, len(arr4) - 1))
    print()

    graph = {
        'A': ['B', 'C', 'D', 'E'],
        'B': ['A', 'C', 'G'],
        'C': ['A', 'B', 'D'],
        'D': ['A', 'C', 'E', 'H'],
        'E': ['A', 'D', 'F'],
        'F': ['E', 'G', 'H'],
        'G': ['B', 'F'],
        'H': ['D', 'F']
    }

    # put neighbors in a reverse order for now
    graph2 = {
        'A': ['E', 'D', 'C', 'B'],
        'B': ['G', 'C', 'A'],
        'C': ['D', 'B', 'A'],
        'D': ['H', 'E', 'C', 'A'],
        'E': ['F', 'D', 'A'],
        'F': ['H', 'G', 'E'],
        'G': ['F', 'B'],
        'H': ['F', 'D']
    }

    print("BREADTH FIRST SEARCH")
    bfs(graph, 'A')
    print()

    print("DEPTH FIRST SEARCH")
    dfs(graph2, 'A')
    print()
Пример #26
0
 def test_ast(self):
     Node(0, 0)