Пример #1
0
def sum_(num1: deque, num2: deque, buf, sum_a_b):
    if num1:
        a = num1.pop()
        if num2:
            b = num2.pop()
            if a + b + buf > 16:
                sum_a_b.appendleft(a + b + buf - 16)
                buf = 1
                sum_(num1, num2, buf, sum_a_b)
            else:
                sum_a_b.appendleft(a + b + buf)
                buf = 0
                sum_(num1, num2, buf, sum_a_b)
        else:
            if a + buf > 16:
                sum_a_b.appendleft(a + buf - 16)
                buf = 1
                sum_(num1, num2, buf, sum_a_b)
            else:
                sum_a_b.appendleft(a + buf)
                buf = 0
                sum_(num1, num2, buf, sum_a_b)
    else:
        if num2:
            b = num2.pop()
            if b + buf > 16:
                sum_a_b.appendleft(b + buf - 16)
                buf = 1
                sum_(num1, num2, buf, sum_a_b)
            else:
                sum_a_b.appendleft(b + buf)
                buf = 0
                sum_(num1, num2, buf, sum_a_b)
        else:
            return sum_a_b.appendleft(buf)
Пример #2
0
def heappop(heap: deque):
    if heap:
        ret_val = heap.popleft()
        if heap:
            last = heap[-1]
            heap.appendleft(last)
            heap.pop()
            length = len(heap)
            idx = 0
            while True:
                left = idx * 2 + 1
                right = idx * 2 + 2
                if left >= length:
                    break
                if right >= length:
                    if heap[idx] > heap[left]:
                        heap[idx], heap[left] = heap[left], heap[idx]
                        idx = left
                    else:
                        break
                else:
                    sm = left if heap[left] < heap[right] else right
                    if heap[idx] > heap[sm]:
                        heap[idx], heap[sm] = heap[sm], heap[idx]
                        idx = sm
                    else:
                        break
        return ret_val
    else:
        return
Пример #3
0
def recursive_combat(p1: deque, p2: deque):
    previous_rounds_1 = list()
    previous_rounds_2 = list()

    while len(p1) > 0 and len(p2) > 0:
        if p1 in previous_rounds_1 and p2 in previous_rounds_2:
            return 1
        previous_rounds_1.append(p1.copy())
        previous_rounds_2.append(p2.copy())

        card1 = p1.pop()
        card2 = p2.pop()

        winner_n = 0
        if len(p1) >= card1 and len(p2) >= card2:
            winner_n = recursive_combat(
                deque(p1[-i] for i in range(card1, 0, -1)),
                deque(p2[-i] for i in range(card2, 0, -1)))
        else:
            if card1 > card2:
                winner_n = 1
            elif card2 > card1:
                winner_n = 2
        if winner_n == 1:
            p1.appendleft(card1)
            p1.appendleft(card2)
        elif winner_n == 2:
            p2.appendleft(card2)
            p2.appendleft(card1)

    return 1 if len(p2) == 0 else 2
Пример #4
0
def bombs(effects: deque, casings: deque):
    type_bombs = {
        "Datura Bombs": [40, 0],
        "Cherry Bombs": [60, 0],
        "Smoke Decoy Bombs": [120, 0],
    }

    success = False

    while effects and casings:
        current_casing = casings[-1]
        current_effect = effects[0]

        for bomb, value in type_bombs.items():
            is_found_bomb = False
            if current_casing + current_effect == value[0]:
                type_bombs[bomb][1] += 1
                casings.pop()
                effects.popleft()
                is_found_bomb = True
                break

        if not is_found_bomb:
            casings[-1] -= 5

        if all([value[1] >= 3 for value in type_bombs.values()]):
            success = True
            break

    return success, type_bombs
def search_solution(states: deque):
    current_state = states[-1]

    if current_state.is_final_state():
        print(" --- Solutions ---")
        visual_validation_bucket = [8, 0, 0]

        for state in states:
            action = state.action

            if action:
                get_water_quality_for_visual_validation(
                    visual_validation_bucket, action)
                print(
                    f"poll {action.amount_of_water}L of water from '{action.poll_from}L bucket' to '{action.add_to}L bucket' -> {visual_validation_bucket}"
                )
            else:
                print(
                    f"water start with 8L, 5L, 3L -> '{visual_validation_bucket}'"
                )

    # trying to use DFS to explore all solutions
    for next_move in explore_next_move(current_state):
        if not is_processed_state(states, next_move):
            states.append(next_move)
            search_solution(states)
            states.pop()
Пример #6
0
def remove_from_right(source_deque: deque, max_remove: int) -> None:
    if max_remove < 0:
        raise ValueError(f'Invalid max ({max_remove}) for deque')
    source_len = len(source_deque) - 1
    for _ in range(max_remove):
        print(f'Removing {source_deque[source_len]} ... ', end='')
        source_deque.pop()
        print(f'-> {source_deque}')
        source_len -= 1
Пример #7
0
 def solve(self, operand: int, sign: str, stack: deque) -> int:
     if sign == '+':
         return operand
     elif sign == '-':
         return -operand
     elif sign == '*':
         return stack.pop() * operand
     elif sign == '/':
         return int(stack.pop() / operand)
Пример #8
0
 def popn(deq: deque):
     n = random.randint(1,2)
     if len(deq) > 0:
         if len(deq) >= n:
             return "".join([deq.pop() for i in range(0,n)])
         else:
             return "".join([deq.pop() for i in range(0,n-1)])
     else:
         return ""
Пример #9
0
def fill_in_line(line_deque: deque):
    score = 0
    while len(line_deque) > 0:
        c = line_deque.pop()
        if c not in match_table.keys():
            line_deque.pop()
        else:
            # need to add bracket
            score = autocomplete_table[match_table[c]] + 5 * score
    return score
Пример #10
0
    def _smallest(self, q1: deque, q2: deque) -> HuffmanNode:
        if len(q1) == 0:
            return q2.pop()

        if len(q2) == 0:
            return q1.pop()

        if q1[-1].count < q2[-1].count:
            return q1.pop()

        return q2.pop()
def _get_all_k_combinations_rec(offset: int, k: int, combination: deque, original_size: int,
                                combinations: deque):
    """ Recursive function to generate all k-combinations. """
    if k == 0:
        combinations.append(deepcopy(combination))
        return

    for i in range(offset, original_size - k + 1, 1):
        combination.append(i)
        _get_all_k_combinations_rec(i + 1, k - 1, combination, original_size, combinations)
        combination.pop()
def task4(arg_deque: deque):
    """
    - Manipulate the `arg_deque` in any order you preferred to achieve the following effect:
        -- remove last element in `deque`
        -- move the fist (left most) element to the end (right most)
        -- add an element `Zack`, a string, to the start (left)
    """
    # your code goes here
    arg_deque.pop() # remove last item
    arg_deque.rotate(-1) # move the first item to end
    arg_deque.appendleft('Zack')
Пример #13
0
def task4(arg_deque: deque):
    """
    - Manipulate the `arg_deque` in any order you preferred to achieve the following effect:
        -- remove last element in `deque`
        -- move the fist (left most) element to the end (right most)
        -- add an element `Zack`, a string, to the start (left)
    """
    # you code starts here:
    arg_deque.pop()
    arg_deque.append(arg_deque.popleft())
    arg_deque.appendleft('Zack')
Пример #14
0
def reverse_linked_list(linked_list):
    s = Stack()
    iter = linked_list.head
    while iter is not None:
        s.append(iter)
        iter = iter.next
    first = s.pop()
    iter = first
    while len(s) > 0:
        iter.next = s.pop()
        iter = iter.next
    iter.next = None
    linked_list.head = first
def append_states(states: collections.deque, count: int) -> np.ndarray:
    # get rid of any extra data we don't need anymore
    while len(states) > count:
        states.pop()
    # if the state deque is not full append zeros, not my favorite thing to do.
    ss = []
    for i in range(count):
        if len(states) > i:
            ss.append(states[i])
        else:
            ss.append(np.zeros(states[0].shape))

    return np.hstack(ss)
def remove(left: deque, right: deque, n):
    for i in range(len(left)):
        left[i] += 0.5
    for i in range(len(right)):
        right[i] -= 0.5
    if left[-1] == n:
        left.pop()
    if right[0] == 0:
        right.popleft()
    if left and right and left[-1] == right[0]:
        r_ant = right.popleft()
        l_ant = left.pop()
        left.append(r_ant)
        right.appendleft(l_ant)
Пример #17
0
def hex_num_sum(number1: deque, number2: deque):
    if len(number2) > len(number1):
        number1, number2 = number2, number1
    result = deque()
    memory = ''
    for _ in range(len(number2)):
        dg1, dg2 = number1.pop(), number2.pop()
        interim_res = hex_digit_calc(dg1, dg2, '+')

        if interim_res is None:
            print("Шестнадцатиричные числа введены некорректно!")
            return None

        # Если на шаге j-1 от суммы получось двухзначное число
        if memory != '':
            # Если на шаге j от суммы получислось двухзначное число
            if len(interim_res) > 1:
                interim_res = interim_res[0] + hex_digit_calc(interim_res[1], memory, '+')
            else:
                interim_res = hex_digit_calc(interim_res, memory, '+')
            memory = ''

        # Сохранение старшего рязряда для шага j+1
        if len(interim_res) > 1:
            result.appendleft(interim_res[1])
            memory = interim_res[0]
        else:
            result.appendleft(interim_res)
    else:
        # Если одного слагаемое больше другого дописываем его остаток к результату
        # с учётом страшего разряда от последней операции в цикле выше
        if len(number1) > 0:
            for _ in range(len(number1)):
                dg1 = number1.pop()
                if memory != '':
                    interim_res = hex_digit_calc(memory, dg1, '+')

                    if len(interim_res) > 1:
                        result.appendleft(interim_res[1])
                        memory = interim_res[0]
                    else:
                        result.appendleft(interim_res)
                        memory = ''
                else:
                    result.appendleft(dg1)
            else:
                if memory != '':
                    result.appendleft(memory)
    return result
Пример #18
0
def query_hanlder(query_entry: Query, dequeue: deque):

    if query_entry.command == "append":
        dequeue.append(query_entry.operand)

    elif query_entry.command == "pop":
        dequeue.pop()

    elif query_entry.command == "popleft":
        dequeue.popleft()

    elif query_entry.command == "appendleft":
        dequeue.appendleft(query_entry.operand)

    return
Пример #19
0
def valid(nrs: deque, tal: int) -> bool:
    """checks if there is a sum of two numbers that adds up to tal"""
    nrs = sorted(nrs)
    nrs = deque(nrs)
    if isinstance(nrs, list):
        raise TypeError('Input is list')
    while len(nrs) >= 1:
        summa = nrs[0] + nrs[-1]
        if summa == tal:
            return True  #correct
        elif summa < tal:  #we need to increase the sum, remove smallest element
            nrs.popleft()
        else:  #need to make it smaller
            nrs.pop()
    return False
Пример #20
0
def hex_sum(hex_0: deque, hex_1: deque, result=None, tail=0) -> deque:
    hex_0, hex_1 = hex_0.copy(), hex_1.copy()
    if not result:  # обнуляем res при каждом вызове func ( -//- за нумером 2)
        result = deque()
        if len(hex_0) != len(hex_1):  # выравниваем списки при необходимости
            hex_0, hex_1 = hex_eq_len(hex_0, hex_1)
    if not hex_0:
        if tail:
            result.appendleft('1')  # добавляем 1 при переполнении
        return result
    spam = HEX_DICT[hex_0.pop()] + HEX_DICT[hex_1.pop()] + tail
    result.appendleft(DEC_DICT[spam]) if spam < BASIS else \
        result.appendleft(DEC_DICT[spam - BASIS])
    tail = 0 if spam < BASIS else 1
    return hex_sum(hex_0, hex_1, result, tail)
    def maxDepth__iterative__depth_first(self, root: TreeNode) -> int:
        """
        Solution to "maximum depth of binary tree" that...
        -   Uses iteration.
        -   Visits nodes in a depth-first order by using a stack.
        """

        from collections import deque as Deck

        #---------------------------------------

        max_depth = 0

        if not root:
            return max_depth

        stack = Deck([(root, 1)])

        while stack:

            (node, depth) = stack.pop()
            next_depth = depth + 1

            if node.left:
                stack.append((node.left, next_depth))

            if node.right:
                stack.append((node.right, next_depth))

            max_depth = max(max_depth, depth)

        return max_depth
Пример #22
0
    def _sample_next_cluster(self, history: deque) -> Tuple[deque, float]:
        """Sample next cluster and corresponding transition time.

        In the key resulting from the current history is not present in the
        list of available transition probabilities, the last cluster label
        in the given history is replaced with the label of the nearest cluster,
        and a new history is searched.

        :param history: current history/past/trajectory
        :type history: deque
        :return: the history with the new cluster appended and the transition time
        :rtype: Tuple[deque, float]
        """
        key = ",".join(map(str, list(history)))
        if not key in self._transition_prob:
            last_cluster = history.pop()
            history.append(self._find_closest_cluster(last_cluster))
            history = self._find_history(history)
            key = ",".join(map(str, list(history)))
        next_cluster = int(
            np.random.choice(self._transition_prob[key][:, 0],
                             p=self._transition_prob[key][:, 1]))
        key += ",{:d}".format(next_cluster)
        history.append(next_cluster)
        return history, self._transition_time[key]
Пример #23
0
def _parse_single_expr_string(tokens: deque) -> str:
    if not is_deque(tokens):
        raise ParseError('Expected expression')
    if tokens[0] == 'not':
        # expression is not(e), so next, parse the expression e before prepending the ~ operator to it.
        token = tokens.pop()
        e = _parse_single_expr_string(token)
        if '~' in e:
            raise ParseError('Multiple not operators in expression.')
        return '~' + e
    else:  # expression is a standard Op(param1, param2, etc ...) format
        expr_name = tokens.popleft()
        if not is_string(expr_name):
            raise ParseError('Invalid expression name: {}'.format(expr_name))
        expr_name = expr_name.lower()
        variables = []
        while tokens:
            param = tokens.popleft()
            if not is_string(param):
                raise ParseError('Invalid parameter {} for expression "{}"'.format(param, expr_name))
            if param.startswith('?'):
                variables.append(param[1:].lower())
            else:
                if not param[0].isupper():
                    param = param.capitalize()
                variables.append(param)
        return build_expr_string(expr_name, variables)
Пример #24
0
    def _status_callback(self, status_deque: deque, exit_event: Event,
                         callback: Callable, wait: float) -> None:
        """Invoke the callback function with the latest job status.

        Args:
            status_deque: Deque containing the latest status.
            exit_event: Event used to notify this thread to quit.
            callback: Callback function to invoke.
            wait: Time between each callback function call.
        """
        while not exit_event.is_set():
            exit_event.wait(wait)

            try:
                status_response = status_deque.pop()
            except IndexError:
                continue

            try:
                status, queue_info = self._get_status_position(
                    ApiJobStatus(status_response['status']),
                    status_response.get('infoQueue', None))
            except IBMQJobApiError as ex:
                logger.warning("Unexpected error when getting job status: %s",
                               ex)
                continue

            callback(self.job_id(), status, self, queue_info=queue_info)
Пример #25
0
def addition_then_multiplication_solver(stack: deque):
    while '+' in stack:
        stack.rotate(-stack.index('+'))
        stack.popleft()
        stack.appendleft(stack.popleft() + stack.pop())

    return reduce((lambda x, y: x * y), (n for n in stack if n != '*'))
Пример #26
0
def pop_three_addition_first(stack: deque):
    window = deque()
    remainder = deque()
    while len(stack) > 0:
        # fill window
        if len(stack) == 1:
            remainder.append(stack.pop())
            break
        for _ in range(3 - len(window)):
            window.append(stack.popleft())
        operand1, operator, operand2 = (window.popleft(), window.popleft(),
                                        window.popleft())
        if operator == '+':
            sum = int(operand1) + int(operand2)
            stack.appendleft(sum)
        else:
            # we have something like 5 * 3 here
            remainder.append(operand1)
            remainder.append(operator)
            window.append(operand2)
    for num in window:
        remainder.append(num)
    while len(remainder) > 1:
        pop_three(remainder)
    stack.append(remainder.pop())
        def is_same_tree(p: MaybeTreeNode, q: MaybeTreeNode) -> bool:
            """Tests `is_same_tree` iteratively, depth-first."""

            stack = Deck([(p, q)])

            while stack:

                (p, q) = stack.pop()

                # If both are empty trees, they are the same.
                if not p and not q:
                    continue

                # Now, if only one is empty, they are not the same.
                # If we got here, then we ruled out both being empty.
                if not p or not q:
                    return False

                # Now, both must be non-empty...

                # If their values are not equal, they are not the same. (Duh!)
                if p.val != q.val:
                    return False

                # Else, then append the left and right branches of `p` and `q` for testing.
                stack.append((p.left, q.left))
                stack.append((p.right, q.right))

            return True
Пример #28
0
    def _traversal(self, nodes: deque) -> List[List[int]]:
        if not nodes:
            return []

        res = []
        is_right_dir = True

        while nodes:
            init_len = len(nodes)
            new_level = []

            for _ in range(init_len):
                if is_right_dir:
                    node = nodes.popleft()
                    if node.left:
                        nodes.append(node.left)
                    if node.right:
                        nodes.append(node.right)
                else:
                    node = nodes.pop()
                    if node.right:
                        nodes.appendleft(node.right)
                    if node.left:
                        nodes.appendleft(node.left)
                new_level.append(node.val)

            res.append(new_level)
            is_right_dir = not is_right_dir

        return res
Пример #29
0
    def get_random_solution(self, curr_time: float, individual: list, unvisited_nodes: list, visited_nodes: deque):
        if len(unvisited_nodes) == 0:
            first_node = self.get_node(individual, visited_nodes[0])
            last_node = self.get_node(individual, visited_nodes[-1])
            full_time = curr_time + last_node["dists"][first_node["index"]]
            cost = self.get_cost(individual, visited_nodes)
            return " ".join(str(visited_nodes[i]) for i in range(1, len(visited_nodes))), full_time, cost
        valid_nodes = self.possible_nodes(
            curr_time, individual, unvisited_nodes, visited_nodes[-1])
        while self.errors <= self.MAX_ERRORS:
            if len(valid_nodes) == 0 and len(unvisited_nodes) != 0:
                self.errors += 1
                return None

            elt = valid_nodes[randrange(len(valid_nodes))]
            last_node = self.get_node(individual, visited_nodes[-1])

            start, end = self.get_time_window(individual, elt)
            arrive_time = curr_time + last_node["dists"][elt]
            new_time = arrive_time if arrive_time > start else start

            unvisited_nodes.remove(elt)
            valid_nodes.remove(elt)
            visited_nodes.append(elt)

            result = self.get_random_solution(
                new_time, individual, unvisited_nodes, visited_nodes)
            if result == None:
                unvisited_nodes.append(visited_nodes.pop())
            else:
                return result
        return None
Пример #30
0
    def reverse_polish(expression: deque) -> float:
        """Computes the value of expresions provided in RPN

        Parameters
        ----------
        expression : deque
            Expression in RPN, typically from `parse` 

        Returns
        -------
        float
            The floating point value of the expression
        """
        evaluation = []

        while len(expression) > 0:
            token = expression.pop()
            if token in '0123456789':
                evaluation.append(token)
            elif token in '+-*/^':
                if token == '^':
                    token = '**'
                operands = [evaluation.pop(), evaluation.pop()]
                evaluation.append(eval(f'{operands[1]} {token} {operands[0]}'))

        return evaluation[0]
Пример #31
0
def peek(stack: deque):
    try:
        top = stack.pop()
        stack.append(top)
    except IndexError:
        top = None
    return top
Пример #32
0
    def analyze_result(self, results: deque, debounce: int, repeat_every: int):
        """Analyze result according to check definition.

        :param results: deque object with last results according to debounce or
        repeat_every
        :param debounce: debounce value from check data
        :param repeat_every: repeat_every value from check data
        :return: (trigger status, event_type)
        :rtype: tuple
        """
        last_result = CachedResult(RESULT_UNKNOWN, RESULT_UNKNOWN, False, "")
        result_length = len(results)
        results_list = list(results)
        if result_length < debounce:
            # not enough values to proceed with analyze
            return RESULT_OK, None

        if result_length == debounce + 1:
            last_result = results.popleft()
        elif result_length == debounce:
            last_result = CachedResult(RESULT_OK, RESULT_OK, False, "")
        elif result_length > debounce:
            last_result = results_list[-(debounce + 1)]

        debounce_probes = results_list[result_length - debounce:]
        all_debounce_fail = all(result.status in FAILED_STATUSES
                                for result in debounce_probes)
        if all([all_debounce_fail, last_result.status in OK_STATUSES]):
            return RESULT_FAILED, 'trigger'

        try:
            if all([all_debounce_fail,
                    results_list[-(repeat_every + 1)].alert_sent]):
                return RESULT_FAILED, 'trigger'
        except IndexError:
            pass

        latest_result = results.pop()
        if all([last_result.status in FAILED_STATUSES,
                all(result.status in FAILED_STATUSES for result in results),
                latest_result.status == RESULT_OK]):

            if latest_result.hysteresis != RESULT_OK:
                return RESULT_FAILED, None

            if latest_result.hysteresis == RESULT_OK:
                return RESULT_OK, 'resolve'
        if all([all(result.status in OK_STATUSES for result in results),
                latest_result.status == RESULT_FAILED]):
            return RESULT_FAILED, None
        if all([all_debounce_fail, last_result.status in FAILED_STATUSES]):
            return RESULT_FAILED, None
        return RESULT_OK, None
Пример #33
0
class spider:
    _plugins = []
    _baseUrl = ""
    _errors = {}

    def __init__(self, plugins, blacklist):
        self._plugins = plugins
        self._visited = set()
        self._queue = Queue()
        self._blacklist = set(blacklist)

    def spider(self, url):
        self._queue.append(url)
        self._baseUrl = url
        try:
            while 1:
                url = self._queue.pop()
                self._visit(url)
        except IndexError:
            pass

    def _visit(self, url):
        if url in self._visited:
            return
        print "visiting: " + url
        self._visited.add(url)
        br = mechanize.Browser()

        try:
            resp = br.open(url)
        except urllib2.HTTPError, e:
            self._errors[e.geturl()] = [e.getcode()]
            return

        if not br.viewing_html():
            return

        for plugin in self._plugins:
            plugin.parsePage(br)

        unique = set()

        for l in br.links():
            if l.absolute_url[0 : len(self._baseUrl)] == self._baseUrl and not l.absolute_url in self._blacklist:
                visitableUrl = l.absolute_url.split("#")[0]
                if not visitableUrl in unique and not visitableUrl in self._visited:
                    self._queue.append(visitableUrl)
                    unique.add(visitableUrl)
                    print "found: " + visitableUrl

        print "visited: " + url