def test_push_pop_elements(self):
     stack = LinkedStack()
     self.assertEqual(stack.count, 0)
     stack.push("WORST")
     el_from_stack = stack.pop()
     self.assertEqual(el_from_stack, "WORST")
     self.assertEqual(stack.count, 0)
 def test_push_pop_thousand_elements(self):
     stack = LinkedStack()
     for idx in range(1000):
         stack.push("WORST BEHAVIOR")
         self.assertEqual(stack.count, idx + 1)
     for idx in range(1000):
         self.assertEqual(stack.count, 1000 - idx)
         self.assertEqual(stack.pop(), "WORST BEHAVIOR")
     self.assertEqual(stack.count, 0)
Esempio n. 3
0
 def __init__(self, timeTable, outfile=None):
     """Starts a trip planning system based on required timetable and
     optional itinerary file for output."""
     self.__timeTable = timeTable
     self.__railways = Graph()
     self.__cities, self.__path = dict(), dict()
     self.__path_stops = LinkedStack()
     self.__outfile = outfile
     self.__origin,self.__destin = None, None
     self._parseTable()
Esempio n. 4
0
 def __init__(self, timeTable, outfile):
     self.__timeTable = timeTable
     self.__railways = Graph()
     self.__cities = dict()
     self.__path = dict()
     self.__path_stops = LinkedStack()
     self.__outfile = outfile
     self.__origin = None
     self.__destin = None
     self._parseTable()
 def test_to_array(self):
     stack = LinkedStack()
     stack.push(3)
     stack.push(5)
     stack.push(-2)
     stack.push(7)
     self.assertEqual(list(stack), [7, -2, 5, 3])
def balanced_parenthese(parenthese):
    stack = LinkedStack()
    for p in parenthese:
        if p == '(':
            stack.push(p)
        else:
            if stack.is_empty():
                return False
            stack.pop()
    return True if stack.is_empty() else False
def prefix_eval(expression):
    num_stack = LinkedStack()
    for e in reversed(expression):
        if e.isdigit():
            num_stack.push(e)
        else:
            num1 = num_stack.pop()
            num2 = num_stack.pop()
            res = eval(num1 + e + num2)
            num_stack.push(str(res))
    return num_stack.pop()
Esempio n. 8
0
    def _fastest(self, origination, destination):
        # TODO simplify and remove duplication shortest path method

        origin = origination.strip().lower()
        dest = destination.strip().lower()
        durations = shortest_path_lengths(self.__railways,
                                          self.__cities[origin])
        orgin_vertex = self.__cities[destination]
        if durations[orgin_vertex] == float("inf"):
            print("There is no connections between {!s} and {!s} in {}.".format(
                origination, destination, self.__timeTable
            ))
            return
        path_map = shortest_path_tree(self.__railways,
                                      self.__cities[origin], durations)

        current_stop = self.__cities[dest]
        self.__path_stops = LinkedStack()
        self.__path_stops.push(current_stop)
        while current_stop != self.__cities[origin]:
            next_stop = path_map[current_stop].opposite(current_stop)
            self.__path[(current_stop,next_stop)] = self.__railways.get_edge(
                current_stop,next_stop).element()
            self.__path_stops.push(next_stop)
            current_stop = next_stop

        path_stops = copy(self.__path_stops)
        duration = 0
        pathString = ''
        while not path_stops.is_empty() and path_stops.top() is not \
                self.__cities[dest]:
            current_stop = path_stops.pop()
            next_stop = path_stops.top()
            duration += self.__railways.get_edge(current_stop,
                                                 next_stop).element()
            pathString += '{!s}{}'.format(current_stop, ' >> ')
        pathString += '{!s}\n'.format(path_stops.pop())
        hours, minutes = duration // 60, duration % 60
        print("The fastest route to", destination, "takes", hours, "hours "
                                                                   "and",
              minutes, "minutes with", len(self.__path_stops),
              "stops as following:")
        print(pathString.title())
def postfix_eval(expression):
    num_stack = LinkedStack()

    for e in expression:
        if e.isdigit():
            num_stack.push(e)
        else:
            num1 = num_stack.pop()
            num2 = num_stack.pop()
            res = eval(num2 + e + num1)
            num_stack.push(str(res))

    return num_stack.pop()    
Esempio n. 10
0
class Evaluate:
    def __init__(self):
        self.exp = LinkedStack()

    def postfix_eval(self, str_exp):
        for i in range(0, len(str_exp)):
            if str_exp[i].isdigit():
                self.exp.push(str_exp[i])
            else:
                val1 = self.exp.pop()
                val2 = self.exp.pop()
                self.exp.push(str(eval(val2 + str_exp[i] + val1)))
        return int(self.exp.pop())
def base_convert(num, base):
    base_str = '0123456789ABCEDF'
    stack = LinkedStack()
    
    while num:
        rem = num % base
        stack.push(rem)
        num = num // base

    output = ''
    while not stack.is_empty():
        output += base_str[stack.pop()]

    return output
Esempio n. 12
0
def bracketsBalance(exp):
    # create new stack
    stk = LinkedStack()
    # scan across the expression
    for ch in exp:
        if ch in ['[', '(']:
            # push opening bracket
            stk.push(ch)
        elif ch in [']', ')']:
            # process closing bracket
            # if stack is empty or, we are at the end of stack, that means this is a floating closing bracket
            if stk.isEmpty():
                return False
            # pop character from top of stack and inspect
            chFromStack = stk.pop()
            # brackets must be of same type and match up
            if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(':
                return False
    return stk.isEmpty()
def infix2prefix(expression):
    res_stack = LinkedStack()
    op_stack = LinkedStack()
    op_priority = {'*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0, ')': 0}

    width = 7 if len(expression) <= 7 else len(expression)
    print(expression[::-1])
    print('Symbol'.center(8),
          'op_stack'.center(width),
          'res_stack'.center(width),
          sep=" | ")
    print('-' * (width * 3 + 7))

    for e in reversed(expression):
        if e == ')':
            op_stack.push(e)

        elif e == '(':
            while op_stack.first() != ')':
                res_stack.push(op_stack.pop())

            op_stack.pop()

        elif e.isdigit():
            res_stack.push(e)

        else:
            while op_stack.first(
            ) and op_priority[e] <= op_priority[op_stack.first()]:
                res_stack.push(op_stack.pop())
            op_stack.push(e)
        print_stack(e, op_stack, res_stack, width)

    while not op_stack.is_empty():
        res_stack.push(op_stack.pop())
    print_stack(' ', op_stack, res_stack, width)

    output = ''
    while not res_stack.is_empty():
        output += res_stack.pop()

    return output
Esempio n. 14
0
class Browser:

    def __init__(self):
        self.forward_stack = LinkedStack()
        self.back_stack = LinkedStack()

    def can_forward(self):
        return not self.forward_stack.is_empty()

    def can_back(self):
        # 容量为1时,不可后退
        if self.back_stack.is_empty() or (self.back_stack.top.next is None):
            print("无法后退!", end="\n")
            return False
        return True

    def open(self, url):
        print("Open new url %s" % url, end="\n")
        self.back_stack.push(url)
        self.forward_stack.pop_all()

    def back(self):
        if self.can_back():
            top = self.back_stack.pop()
            self.forward_stack.push(top)
            current = self.back_stack.top.data
            print("back to %s" % current, end="\n")

    def forward(self):
        if self.can_forward():
            top = self.forward_stack.pop()
            self.back_stack.push(top)
            print("forward to %s" % top, end="\n")
Esempio n. 15
0
class Browser():
    '''
    使用两个栈模拟浏览器前进后退
    '''

    def __init__(self):
        self.forward_stack = LinkedStack()
        self.back_stack = LinkedStack()

    def can_forward(self):
        if self.back_stack.is_empty():
            return False

        return True

    def can_back(self):
        if self.forward_stack.is_empty():
            return False

        return True

    def open(self, url):
        print(f"打开新地址: {url}")
        self.forward_stack.push(url)

    def back(self):
        if self.forward_stack.is_empty():
            return

        top = self.forward_stack.pop()
        self.back_stack.push(top)
        print(f"后退至: {top}")

    def forward(self):
        if self.back_stack.is_empty():
            return

        top = self.back_stack.pop()
        self.forward_stack.push(top)
        print(f"前进至: {top}")
Esempio n. 16
0
 def __init__(self):
     self.forward_stack = LinkedStack()
     self.back_stack = LinkedStack()
Esempio n. 17
0
    def __init__(self):
        '''
		初始化。
		'''
        self.__stack_x = LinkedStack(5)
        self.__stack_y = LinkedStack(5)
Esempio n. 18
0
class TripPlanner:
    """Trip Planner is a path finder class which finds shortest possible route
    between two cities in a routing system using Dijkstra's Algorithm ."""

    def __init__(self, timeTable, outfile=None):
        """Starts a trip planning system based on required timetable and
        optional itinerary file for output."""
        self.__timeTable = timeTable
        self.__railways = Graph()
        self.__cities, self.__path = dict(), dict()
        self.__path_stops = LinkedStack()
        self.__outfile = outfile
        self.__origin,self.__destin = None, None
        self._parseTable()

    def _parseTable(self):
        routes = set()
        print("File Loading...")
        with open(self.__timeTable, 'r') as timeTable:
            for line in timeTable.readlines():
                s, d, w = line.strip().lower().split(',')
                duration = int(w.split(':')[0]) * 60 + int(w.split(':')[1])
                if s not in self.__cities:
                    self.__cities.setdefault(s)
                    self.__cities[s] = self.__railways.insert_vertex(s)
                if d not in self.__cities:
                    self.__cities.setdefault(d)
                    self.__cities[d] = self.__railways.insert_vertex(d)
                self.__railways.insert_edge(self.__cities[s],
                                            self.__cities[d], duration)
        print(self)

    def UI(self):
        """Starts User Interface which asks for origination and destination in
        a rail system and return the fastest possible route if existed."""
        print('-' * 75)
        print("Welcome to the path finder. You can enter your current city\n"
              "and destination for the fastest possible trip in",
              self.__timeTable.split('.')[0], '.')
        while True:
            origination = input("Please enter an origination: ")
            destination = input("Please enter a destination: ")
            if origination.strip().lower() not in self.__cities:
                print("Oops,", origination, "was not found in the rail system!"
                                            " Please try again!")
            elif destination.strip().lower() not in self.__cities:
                print("Oops,", destination, "was not found in the rail system!"
                                            " Please try again!")
            else:
                self.__origin = self.__cities[origination.strip().lower()]
                self.__destin = self.__cities[destination.strip().lower()]
                self._shrotest(origination, destination)
            prompt = input("Do you want to quit?(y/n)")
            if prompt.startswith('y'):
                break
        if self.__outfile is not None:
            self.dump()

    def _shrotest(self, origination, destination):
        origin = origination.strip().lower()
        destin = destination.strip().lower()
        durations = shortest_path_lengths(self.__railways,
                                          self.__cities[origin])
        origin_vertex = self.__cities[destin]
        if durations[origin_vertex] == float("inf"):
            print("Sorry, there is no rail connections between {!s} and {!s} in "
                  "{}. Try other rail systems.".format(
                origination, destination, self.__timeTable))
            return
        path_map = shortest_path_tree(self.__railways,
                                      self.__cities[origin], durations)

        current_stop = self.__cities[destin]
        self.__path_stops = LinkedStack()
        self.__path_stops.push(current_stop)
        while current_stop != self.__cities[origin]:
            next_stop = path_map[current_stop].opposite(current_stop)
            self.__path[(current_stop, next_stop)] = self.__railways.get_edge(
                current_stop, next_stop).element()
            self.__path_stops.push(next_stop)
            current_stop = next_stop

        path_stops = copy(self.__path_stops)
        duration = 0
        pathString = ''
        while not path_stops.is_empty() and path_stops.top() is not \
                self.__cities[destin]:
            current_stop = path_stops.pop()
            next_stop = path_stops.top()
            duration += self.__railways.get_edge(current_stop,
                                                 next_stop).element()
            pathString += '{!s}{}'.format(current_stop, ' >> ')
        pathString += '{!s}\n'.format(path_stops.pop())
        hours, minutes = duration // 60, duration % 60
        print("The fastest route to", destination, "takes", hours, "hours "
                                                                   "and",
              minutes, "minutes with", len(self.__path_stops),
              "stops as following:")
        print(pathString.title())

    def dump(self):
        """Exports most recent found shortest path between requested cities
        to a gv file."""
        style, shape = '', ''
        stops = set()
        endpoints = self.__origin, self.__destin
        routeTitle = self.__timeTable.split('.')[0]

        visual_graph = open(self.__outfile, 'w')
        visual_graph.write("graph {} {}\n".format(routeTitle, '{'))
        for cities in self.__path:
            stops |= {cities[0], cities[1]}
        visual_graph.write('{}[shape=octagon,style=filled,'
                           'color="darkgreen"]\n'.format(
                            str(self.__origin).title()))
        visual_graph.write('{}[shape=octagon,style=filled,'
                           'color="skyblue"]\n'.format(
                            str(self.__destin).title()))
        for stop in stops:
            if stop not in endpoints:
                style = 'style=bold'
                shape = ''
                if self.__railways.degree(stop) > 3:
                    shape = ', shape=doublecircle'
                stop = str(stop).title()
                visual_graph.write('{}[{}{}]\n'.format(stop, style, shape))
        for route in self.__railways.edges():
            v, u = route.endpoints()
            hours, mins = route.element() // 60, route.element() % 60
            style = ''
            if (v, u) in self.__path or (u, v) in self.__path:
                style = " ,style=bold"
            else:
                style = ""
            v, u = str(v).title(), str(u).title()
            visual_graph.write('{} -- {} [label="{}h {}m"{}]\n'.format(
                v, u, hours, mins, style))
        visual_graph.write("}")

    def __str__(self):
        """Returns number of cities and rail roads in the parsed timetable."""
        output = "There are {!s} cities with {!s} connections in {}.".format(
            self.__railways.vertex_count(), self.__railways.edge_count(),
            self.__timeTable.split('.')[0])
        return output
def infix2postfix(expression):
    output = []
    op_stack = LinkedStack()
    op_priority = {'*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0, ')': 0}

    for e in expression:
        if e == '(':
            op_stack.push(e)
        elif e == ')':
            while op_stack.first() != '(':
                output.append(op_stack.pop())
            op_stack.pop()
        elif e.isdigit():
            output.append(e)
        else:
            while not op_stack.is_empty() and op_priority[op_stack.first()] >= op_priority[e]:
                output.append(op_stack.pop())
            op_stack.push(e) 
    
    while not op_stack.is_empty():
        output.append(op_stack.pop())

    return ''.join(output)
 def test_pop_empty_stack(self):
     stack = LinkedStack()
     with self.assertRaises(Exception):
         stack.pop()
Esempio n. 21
0
 def __init__(self):
     self.exp = LinkedStack()
 def test_empty_to_array(self):
     self.assertEqual(list(LinkedStack()), [])
Esempio n. 23
0
class Browser(object):
    """
	定义浏览器类。
	"""
    def __init__(self):
        '''
		初始化。
		'''
        self.__stack_x = LinkedStack(5)
        self.__stack_y = LinkedStack(5)

    def open(self, url):
        '''
		访问新页面。
		'''
        print("Open new url %s" % url, end="\n")
        self.__stack_x.push(url)

    def forward(self):
        '''
		前进。
		'''
        top = self.__stack_y.pop()
        if top:
            self.__stack_x.push(top.data)
            print("from %s forward to %s" %
                  (self.__stack_x.head.next.data, top.data),
                  end="\n")
        else:
            print('can not to forward!')

    def back(self):
        '''
		后退。
		'''
        top = self.__stack_x.pop()
        if top:
            self.__stack_y.push(top.data)
            print("from %s back to %s" % (top.data, top.next.data), end="\n")
        else:
            print('can not to back!')

    def clear(self):
        '''
		清空栈。
		'''
        self.__stack_y.clear()

    def print_all(self):
        '''
		打印栈中所有元素。
		'''
        self.__stack_x.print_all()
        self.__stack_y.print_all()