예제 #1
0
 def test_queue(self):
     test_queue = Queue()
     for i in range(0, 5):
         test_queue.push(i)
     counter = 0
     while test_queue.is_empty() is not True:
         self.assertTrue(test_queue.peek() == counter)
         test_queue.pop()
         counter += 1
     self.assertTrue(test_queue.is_empty())
예제 #2
0
    def shunting_yard(self, elements: Queue):
        """Does the shunting yard algorithm to produce something that is ready for rpn"""
        operator_stack = Stack()
        while not elements.is_empty():
            element = elements.pop()

            if isinstance(element, numbers.Number):
                self.output_queue.push(element)
            elif isinstance(element, Function) or element == "(":
                operator_stack.push(element)
            elif element == ")":
                while operator_stack.peek() != "(":
                    self.output_queue.push(operator_stack.pop())

                # Pop (
                if operator_stack.peek() == "(":
                    operator_stack.pop()

                if not operator_stack.is_empty() and isinstance(operator_stack.peek(), Function):
                    self.output_queue.push(operator_stack.pop())
            elif isinstance(element, Operator):
                intermediate_storage = Stack()
                while ((not operator_stack.is_empty())
                       and (not operator_stack.peek() == "(")
                       and operator_stack.peek().strength < element.strength):
                    intermediate_storage.push(operator_stack.pop())

                while not intermediate_storage.is_empty():
                    operator_stack.push(intermediate_storage.pop())

                operator_stack.push(element)

        while not operator_stack.is_empty():
            self.output_queue.push(operator_stack.pop())
예제 #3
0
    def test_queue(self):
        """Test Queue class"""

        queue = Queue()
        for num in self.test_list:
            queue.push(num)

        index = 0
        while not queue.is_empty():
            num = queue.pop()
            self.assertEqual(num, self.test_list[index])
            index += 1
예제 #4
0
class Dispatcher:
    """A dispatcher fulfills requests from riders and drivers for a
    ride-sharing service.

    When a rider requests a driver, the dispatcher assigns a driver to the
    rider. If no driver is available, the rider is placed on a waiting
    list for the next available driver. A rider that has not yet been
    picked up by a driver may cancel their request.

    When a driver requests a rider, the dispatcher assigns a rider from
    the waiting list to the driver. If there is no rider on the waiting list
    the dispatcher does nothing. Once a driver requests a rider, the driver
    is registered with the dispatcher, and will be used to fulfill future
    rider requests.
    """
    def __init__(self):
        """Initialize a Dispatcher.

        @type self: Dispatcher
        @type _waitlist: Queue of Rider
        @type _fleet: PriorityQueue of Driver
        @rtype: None
        """
        self._waitlist = Queue()
        self._fleet = []

    def request_driver(self, rider):
        """Return a driver for the rider, or None if no driver is available.

        Add the rider to the waiting list if there is no available driver.

        @type self: Dispatcher
        @type rider: Rider
        @rtype: Driver | None

        >>> d = Dispatcher()
        >>> d1 = Driver('a', Location(9,0), 1)
        >>> d2 = Driver('b', Location(0,0), 1)
        >>> d._fleet = [d1, d2]
        >>> r1 = Rider('a', Location(0,0), Location(1,0), 3)
        >>> print(d.request_driver(r1))
        a
        """
        fastest_driver = self._fleet[0]

        for driver in self._fleet:
            if not driver.is_idle:
                self._waitlist.add(rider)
                return None
            else:
                for i in range(len(self._fleet) - 1):
                    for j in range(len(self._fleet) - 1):
                        if self._fleet[i].get_travel_time(rider.origin) \
                                < self._fleet[j].get_travel_time(rider.origin):
                            fastest_driver = self._fleet[i]
                        else:
                            fastest_driver = self._fleet[j]

        return fastest_driver

    def request_rider(self, driver):
        """Return a rider for the driver, or None if no rider is available.

        If this is a new driver, register the driver for future rider requests.

        @type self: Dispatcher
        @type driver: Driver
        @rtype: Rider | None

        >>> d = Dispatcher()
        >>> r1 = Rider('a', Location(0,0), Location(1,0), 3)
        >>> d._waitlist = Queue()
        >>> d._waitlist.add(r1)
        >>> d1 = Driver('a', Location(0,0), 1)
        >>> d2 = Driver('b', Location(0,0), 1)
        >>> d._fleet = [d1]
        >>> print(d.request_rider(d2))
        a
        >>> print(d._fleet)
        """
        if driver not in self._fleet:
            self._fleet.append(driver)

        # If waitlist is not empty, assign a rider
        if not self._waitlist.is_empty():
            return self._waitlist.remove()
        else:
            return None

    def cancel_ride(self, rider):
        """Cancel the ride for rider and change their status to CANCELLED.

        @type self: Dispatcher
        @type rider: Rider
        @rtype: None
        """
        rider._status = CANCELLED
        self._waitlist.remove(rider)
예제 #5
0
class Dispatcher:
    """A dispatcher fulfills requests from riders and drivers.

    When a rider requests a driver, the dispatcher assigns a driver to the
    rider. If no driver is available, the rider is placed on a waiting
    list for the next available driver. A rider that has not yet been
    picked up by a driver may cancel their request.

    When a driver requests a rider, the dispatcher assigns a rider from
    the waiting list to the driver. If there is no rider on the waiting list
    the dispatcher does nothing. Once a driver requests a rider, the driver
    is registered with the dispatcher, and will be used to fulfill future
    rider requests.
    """
    def __init__(self):
        """Initialize a Dispatcher.

        @type self: Dispatcher
        @type waiting_riders
        @type availalbe_drivers
        @rtype: None
        """

        self._available_drivers = []
        self._waiting_riders = Queue()

    def __str__(self):
        """Return a string representation.

        @type self: Dispatcher
        @rtype: str
        """

        return "Dispatcher:\n   waiting_riders {0}, \n  availalbe_drivers {1}"\
            .format(self._waiting_riders, self._available_drivers)

    def request_driver(self, rider):
        """Return a driver for the rider, or None if no driver is available.

        Add the rider to the waiting list if there is no available driver.
        If there are available drivers, return the one that can reach the driver fastest


        @type self: Dispatcher
        @type rider: Rider
        @rtype: Driver | None
        """

        if len(self._available_drivers) == 0:
            self._waiting_riders.add(rider)
            return None

        DriverTimes = []
        for driver in self._available_drivers:
            if driver.is_idle:
                DriverTimes.append(driver.get_travel_time(rider.origin))
        shortestTime = min(DriverTimes)

        for driver in self._available_drivers:
            if driver.get_travel_time(rider.origin) == shortestTime:
                return driver

    def request_rider(self, driver):
        """Return a rider for the driver, or None if no rider is available.

        If this is a new driver, register the driver for future rider requests.
        Return None if no riders are available, otherwise return the longest waiting rider.

        @type self: Dispatcher
        @type driver: Driver
        @rtype: Rider | None
        """

        if not driver in self._available_drivers:
            self._available_drivers.append(driver)

        if self._waiting_riders.is_empty():
            return None

        # The longest waiting rider if the first element of self.waiting_riders
        return self._waiting_riders.remove()

    def cancel_ride(self, rider):
        """Cancel the ride for rider.

        @type self: Dispatcher
        @type rider: Rider
        @rtype: None

        >>> John = Dispatcher()
        >>> Bobby = Rider('Bobby', Location(1,2), Location(3,4), 10)
        >>> John._waiting_riders.items = [Bobby]
        >>> John.cancel_ride(Bobby)
        >>> print(John._waiting_riders.items)
        []

        """

        if rider in self._waiting_riders.items:
            self._waiting_riders.items.remove(rider)
예제 #6
0
class calculator:
    def __init__(self):
        self.functions = {
            'EXP': Function(numpy.exp),
            'LOG': Function(numpy.log),
            'SIN': Function(numpy.sin),
            'COS': Function(numpy.cos),
            'SQRT': Function(numpy.sqrt),
            'SQUARE': Function(numpy.square)
        }

        self.operators = {
            'PLUSS': Operator(numpy.add, 0),
            'GANGE': Operator(numpy.multiply, 1),
            'DELE': Operator(numpy.divide, 1),
            'MINUS': Operator(numpy.subtract, 0)
        }
        self.output_queue = Queue()

    def RPN(self):
        stack = Stack()
        while not self.output_queue.is_empty():
            ele = self.output_queue.pop()
            if isinstance(ele, float):
                stack.push(ele)
            elif ele in self.functions.keys():
                ele2 = stack.pop()
                stack.push(self.functions[ele].execute(ele2))
            elif ele in self.operators.keys():
                ele2 = stack.pop()
                ele3 = stack.pop()
                stack.push(self.operators[ele].execute(ele3, ele2))
        return stack.pop()

    def shunting_yard(self, string_regn):
        op_strong = "GANGE,DELE"
        op_stack = Stack()
        for ele in string_regn:
            if ele.isdigit() or ele[0] == '-':
                self.output_queue.push(float(ele))
            elif ele in self.functions.keys() or ele == "(":
                op_stack.push(ele)
            elif ele == ")":
                num = op_stack.pop()
                while num != "(":
                    self.output_queue.push(num)
                    num = op_stack.pop()
            if ele in self.operators.keys():
                peek = op_stack.peek()
                if peek:
                    if peek in op_strong:
                        self.output_queue.push(op_stack.pop())
                op_stack.push(ele)
            # print(op_stack.items)
            # print(self.output_queue.items)
        while not op_stack.is_empty():
            self.output_queue.push(op_stack.pop())
            # print(self.output_queue.items)
        return self.RPN()

    def string_parser(self, text):
        text.replace(" ", "")
        regex = '[-A-Z/(*/)*a-z0-9]+'
        #regex = '[-A-Za-z0-9]+'
        list1 = re.findall(regex, text)
        list3 = re.findall('[/(*/)*]+', text)
        list2 = []
        count_par = 0
        for i in list1:
            if '(' in i:
                num = i.count('(')
                self.split_par(i, list2, '(', num, list3, count_par)
                count_par += 1
            elif ')' in i:
                num = i.count(')')
                self.split_par(i, list2, ')', num, list3, count_par)
                count_par += 1
            else:
                list2.append(i)
        # print(list2)
        return self.shunting_yard(list2)

    def split_par2(self, i, list2, par, num):
        start_par = i.split(par)
        count = 0
        for ele in start_par:
            if ele != "":
                print(ele)
                list2.append(ele)
                for j in range(num):
                    list2.append(par)
                count += 2
        if count > len(start_par) + 1 + num:
            list2.pop(-1)
        return list2

    def split_par(self, i, list2, par, num, list3, count_par):
        start_par = i.split(par)
        count = 0
        for ele in start_par:
            if ele != "":
                list2.append(ele)
                for i in range(len(list3[count_par])):
                    list2.append(par)
                count += 2
        if count > len(start_par) + 1 + num:
            list2.pop(-1)
        return list2
예제 #7
0
class Calc:
    """Calcualtor for evaluation different expressions"""

    def __init__(self):
        self.functions = {
            'EXP': Function(np.exp),
            'LOG': Function(np.log),
            'SIN': Function(np.sin),
            'COS': Function(np.cos),
            'SQRT': Function(np.sqrt)
        }
        self.operators = {
            'PLUS': Operator(np.add, 0),
            'ADD': Operator(np.add, 0),
            'TIMES': Operator(np.multiply, 1),
            'MULTIPLY': Operator(np.multiply, 1),
            'DIVIDE': Operator(np.divide, 1),
            'MINUS': Operator(np.subtract, 0),
            'SUBTRACT': Operator(np.subtract, 0)
        }

        self.output_queue = Queue()

    def calculate_expression(self, text):
        """Takes an expression in human readable form and calculates the answer"""
        text = self.parse_text(text)
        self.shunting_yard(text)
        answer = self.rpn()
        return answer

    def parse_text(self, text):
        """Parses human readable text into something that is ready to be sorted by shunting_yard"""
        text = text.replace(" ", "").upper()
        index = 0
        shunting_yard_ready = Queue()

        while index < len(text):
            text = text[index:]

            # Check for number
            match = re.search("^[-0123456789.]+", text)
            if match is not None:
                shunting_yard_ready.push(float(match.group(0)))
                index = match.end(0)
                continue

            # Check for function
            match = re.search("|".join(["^" + func for func in self.functions.keys()]), text)
            if match is not None:
                shunting_yard_ready.push(self.functions[match.group(0)])
                index = match.end(0)
                continue

            # Check for operator
            match = re.search("|".join(["^" + op for op in self.operators.keys()]), text)
            if match is not None:
                shunting_yard_ready.push(self.operators[match.group(0)])
                index = match.end(0)
                continue

            # Check for paranthases
            match = re.search("^[()]", text)
            if match is not None:
                shunting_yard_ready.push(match.group(0))
                index = match.end(0)
                continue

        return shunting_yard_ready

    def shunting_yard(self, elements: Queue):
        """Does the shunting yard algorithm to produce something that is ready for rpn"""
        operator_stack = Stack()
        while not elements.is_empty():
            element = elements.pop()

            if isinstance(element, numbers.Number):
                self.output_queue.push(element)
            elif isinstance(element, Function) or element == "(":
                operator_stack.push(element)
            elif element == ")":
                while operator_stack.peek() != "(":
                    self.output_queue.push(operator_stack.pop())

                # Pop (
                if operator_stack.peek() == "(":
                    operator_stack.pop()

                if not operator_stack.is_empty() and isinstance(operator_stack.peek(), Function):
                    self.output_queue.push(operator_stack.pop())
            elif isinstance(element, Operator):
                intermediate_storage = Stack()
                while ((not operator_stack.is_empty())
                       and (not operator_stack.peek() == "(")
                       and operator_stack.peek().strength < element.strength):
                    intermediate_storage.push(operator_stack.pop())

                while not intermediate_storage.is_empty():
                    operator_stack.push(intermediate_storage.pop())

                operator_stack.push(element)

        while not operator_stack.is_empty():
            self.output_queue.push(operator_stack.pop())

    def rpn(self):
        """Evaluates self.output_queue in RPN"""
        intermediate_storage = Stack()
        while not self.output_queue.is_empty():
            item = self.output_queue.pop()
            if isinstance(item, numbers.Number):
                intermediate_storage.push(item)
            elif isinstance(item, Function):
                result = item.execute(intermediate_storage.pop())
                intermediate_storage.push(result)
            elif isinstance(item, Operator):
                operand1 = intermediate_storage.pop()
                operand2 = intermediate_storage.pop()
                result = item.execute(operand2, operand1)
                intermediate_storage.push(result)

        return intermediate_storage.pop()