Exemple #1
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 != '*'))
def do_rotations_B(source_deque: deque, rot_cnt: int) -> None:
    print('-' * 60)
    tmp_cnt = 1
    while rot_cnt > 0:
        source_deque.rotate()
        print(f'Rotation-B #{tmp_cnt}: {source_deque}')
        tmp_cnt += 1
        rot_cnt -= 1
Exemple #3
0
def rotaciona(d: deque, n: int):
    # O método rotate considera n > 0 para
    #   rotações 'anti-horárias' (da direita para a esquerda)
    #   e n < 0 para rotações 'horárias' (esqueda para a direita)
    #
    # declaro essa função auxiliar que inverte o sinal só
    # para que a explicação esteja no contexto do exemplo.
    d.rotate(-n)
Exemple #4
0
    def _create_part(self, attach_lanes, attach_road: Road, radius: float,
                     intersect_nodes: deque, part_idx) -> (StraightLane, bool):
        lane_num = self.lane_num_intersect if part_idx == 0 or part_idx == 2 else self.positive_lane_num
        non_cross = True
        attach_left_lane = attach_lanes[0]
        # first left part
        assert isinstance(
            attach_left_lane, StraightLane
        ), "Can't create a intersection following a circular lane"
        self._create_left_turn(radius, lane_num, attach_left_lane, attach_road,
                               intersect_nodes, part_idx)

        # u-turn
        if self.enable_u_turn:
            adverse_road = -attach_road
            self._create_u_turn(attach_road, part_idx)

        # go forward part
        lanes_on_road = copy.deepcopy(attach_lanes)
        straight_lane_len = 2 * radius + (2 * lane_num -
                                          1) * lanes_on_road[0].width_at(0)
        for l in lanes_on_road:
            next_lane = ExtendStraightLane(l, straight_lane_len,
                                           (LineType.NONE, LineType.NONE))
            self.block_network.add_lane(attach_road.end_node,
                                        intersect_nodes[1], next_lane)

        # right part
        length = self.EXIT_PART_LENGTH
        right_turn_lane = lanes_on_road[-1]
        assert isinstance(
            right_turn_lane, StraightLane
        ), "Can't create a intersection following a circular lane"
        right_bend, right_straight = create_bend_straight(
            right_turn_lane, length, radius, np.deg2rad(self.ANGLE), True,
            right_turn_lane.width_at(0), (LineType.NONE, LineType.SIDE))

        non_cross = (not check_lane_on_road(
            self._global_network,
            right_bend,
            1,
            ignore_intersection_checking=self.ignore_intersection_checking)
                     ) and non_cross
        CreateRoadFrom(
            right_bend,
            min(self.positive_lane_num, self.lane_num_intersect),
            Road(attach_road.end_node, intersect_nodes[0]),
            self.block_network,
            self._global_network,
            toward_smaller_lane_index=True,
            side_lane_line_type=LineType.SIDE,
            inner_lane_line_type=LineType.NONE,
            center_line_type=LineType.NONE,
            ignore_intersection_checking=self.ignore_intersection_checking)

        intersect_nodes.rotate(-1)
        right_straight.line_types = [LineType.BROKEN, LineType.SIDE]
        return right_straight, non_cross
Exemple #5
0
def deal(d: deque, count: int = 0) -> None:
    if count == 0:
        d.reverse()
        return

    _d: deque = d.copy()
    while len(_d):
        d[0] = _d.popleft()
        d.rotate(-count)
Exemple #6
0
def run(numbers_queue: deque, lengths: List[int], position: int = 0, skip_size: int = 0) -> Tuple[deque, int, int]:
    for length in lengths:
        numbers_list = list(numbers_queue)
        numbers_queue = deque(numbers_list[:length][::-1] + numbers_list[length:])
        rotation = (length + skip_size) % len(numbers_queue)
        position += length + skip_size
        numbers_queue.rotate(-rotation)
        skip_size += 1
    return numbers_queue, position, skip_size
def is_dot_in_polygon(dot: Point, hull: deque):
    if len(hull) == 2:
        if ccw(hull[0], hull[1], dot) == 0 and hull[0].y < dot.y < hull[1].y:
            return True
        return False

    for _ in range(len(hull)):
        if ccw(hull[0], hull[1], dot) <= 0:
            return False
        hull.rotate()
    return True
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')
Exemple #9
0
def is_right_parenthesis(d: deque, n: int) -> int:
    d.rotate(n)
    stack = []
    while d:
        token = d.popleft()
        if token in parenthesises.values():
            stack.append(token)
            continue
        if not stack or stack[-1] != parenthesises[token]:
            return 0
        stack.pop()
    return 1 if not stack else 0
Exemple #10
0
def rotate(directions: deque, move: str, delta: int) -> deque:
    logging.debug(f'enter rotate')
    logging.debug(f'{move} - {delta} - {int(delta/90)}')
    logging.debug(f'{directions}')
    rotation = int(delta/90)
    logging.debug(rotation)
    if move == 'R':
        directions.rotate(-rotation)
    else: # move == 'L'
        directions.rotate(rotation)

    logging.debug(f'{directions}')
    return directions
Exemple #11
0
def iteration(p: deque, c_pos: int):
    c_pos %= len(p)
    p.rotate(-c_pos)
    sel = []
    for _ in range(3):
        v = p[1]
        sel.append(v)
        p.remove(v)
    d_value = calc_dest_value(p, sel, p[0])
    d_pos = p.index(d_value) + 1
    for i in range(3):
        p.insert(d_pos + i, sel[i])
    p.rotate(c_pos)
Exemple #12
0
def crab_move(cups: deque) -> deque:
    """Performs a single crab move. Each move, the crab does the following actions:
    1) The crab picks up the three cups that are immediately clockwise of the
       current cup. They are removed from the circle; cup spacing is adjusted as
       necessary to maintain the circle.
    2) The crab selects a destination cup: the cup with a label equal to the
       current cup's label minus one. If this would select one of the cups that
       was just picked up, the crab will keep subtracting one until it finds a
       cup that wasn't just picked up. If at any point in this process the value
       goes below the lowest value on any cup's label, it wraps around to the
       highest value on any cup's label instead.
    3) The crab places the cups it just picked up so that they are immediately
       clockwise of the destination cup. They keep the same order as when they
       were picked up.
    4) The crab selects a new current cup: the cup which is immediately clockwise
       of the current cup.

    **Note 1: the input `cups` should always be structured such that the
      "current cup" is positioned at index -1 (i.e. a "reversed" list).
    **Note 2: deque is preferred over lists in the cases where we need quicker
      append and pop operations from both the ends of the container; deque provides
      an O(1) time complexity for append and pop operations as compared to
      lists, which provide O(n) time complexity (source: GeeksForGeeks).
    """
    # action 4  (**note: we do it here so we can do pop() immediately below)
    cups.rotate(1)  # shift the current cup to the end of the queue

    # action 1
    three_cups = [cups.pop() for _ in range(3)]

    # action 2
    destination_cup = cups[0] - 1
    while destination_cup in three_cups or destination_cup < 1:
        destination_cup -= 1
        if destination_cup < 0:
            destination_cup = max(cups)

    destination_cup_idx = cups.index(destination_cup)

    # action 3
    cups.insert(destination_cup_idx, three_cups[0])
    cups.insert(destination_cup_idx, three_cups[1])
    cups.insert(destination_cup_idx, three_cups[2])

    return cups
Exemple #13
0
def play_cups(cups: deque, nb_moves):
    for i in range(0, nb_moves):
        #print(f'-- move {i+1} --')
        current_cup = cups[0]

        # print(cups)
        # print(f'current: {current_cup}')

        cups.rotate(-1)

        pickups = [cups.popleft(), cups.popleft(), cups.popleft()]
        destination_cup = get_destination(current_cup, cups)

        # print(f'pick up: {pickups}')
        # print(f'destination: {destination_cup}')

        dest_in = cups.index(destination_cup)

        # push dest to end right end of the queue
        # and add pickups to the right
        cups.rotate(-dest_in - 1)
        cups.extend(pickups)

        # rotate the queue back into initial state shifted once
        cups.rotate(dest_in + 4)
        # print('')

    return cups
Exemple #14
0
def play_game_one(cups: deque, n_moves: int) -> deque:
    for _ in range(n_moves):
        current_cup_value = cups[0]
        cups.rotate(-1)
        pick_up = deque()
        for _ in range(3):
            pick_up.append(cups.popleft())

        destination_cup = None
        destination_cup_value = current_cup_value - 1
        while True:
            if destination_cup_value < min(cups):
                destination_cup_value = max(cups)
            try:
                destination_cup = cups.index(destination_cup_value)
                break
            except ValueError:
                destination_cup_value -= 1
                continue

        for i in range(3):
            cups.insert((destination_cup + i + 1) % len(cups), pick_up[i])

    return cups
Exemple #15
0
def crab_moves_cups(cups: deque, rounds=10):
    current = cups[0]
    mini = min(cups)
    maxi = max(cups)
    l = len(cups)
    init_time = time.time()
    for turn in range(rounds):
        if turn % 500 == 0:
            duration = time.time() - init_time
        current = cups.popleft()
        picked = [cups.popleft() for _ in range(3)]
        cups.appendleft(current)
        destination = current - 1
        while destination in picked or destination < mini:
            destination -= 1
            if destination < mini:
                destination = maxi
        # THIS is slow: searching a value in a deque
        destination_index = cups.index(destination) + 1
        for add in reversed(picked):
            cups.insert(destination_index, add)
        # The crab selects a new current cup: the cup which is immediately clockwise of the current cup.
        cups.rotate(-1)  # this places the new current cup at the beginning of the deque
    return cups
Exemple #16
0
def part1(input: deque):
    min_cup, max_cup = min(input), max(input)
    for i in range(100):
        current = max_cup if input[0] == min_cup else input[0] - 1
        input.rotate(-1)
        one, two, three = input.popleft(), input.popleft(), input.popleft()
        while current == one or current == two or current == three:
            current = max_cup if current == min_cup else current - 1

        destination = input.index(current) + 1

        input.rotate(-1 * destination)
        input.extendleft((three, two, one))
        input.rotate(destination)

    destination = input.index(1)
    input.rotate(-1 * destination)
    input.popleft()
    return "".join(map(str, input))
def calc_move(arr: deque) -> deque:
    current_cup_value = arr[0]
    arr.rotate(-1)
    pick_up_values = [arr.popleft() for _ in range(3)]
    destination_cup_index = get_destination_cup(arr, pick_up_values,
                                                current_cup_value)
    arr.rotate(-destination_cup_index - 1)
    arr.appendleft(pick_up_values[2])
    arr.appendleft(pick_up_values[1])
    arr.appendleft(pick_up_values[0])
    arr.rotate(-(-destination_cup_index - 1))

    return arr
Exemple #18
0
def perform_move(cups: deque):
    min_cup, max_cup = min(cups), max(cups)
    current = cups[0]
    cups.rotate(-1)
    picked_up = [cups.popleft() for _ in range(3)]

    destination = current - 1
    while destination in picked_up or destination < min_cup:
        if destination < min_cup:
            destination = max_cup
        else:
            destination -= 1

    position = cups.index(destination) + 1
    cups.rotate(-position)
    cups.extendleft(picked_up[::-1])
    cups.rotate(position)
    return cups
Exemple #19
0
def cutNCards(cards: deque, n: int):
    cards.rotate(-n)
    if verbose: print(f"cut {n}: {cards}")
    return cards
Exemple #20
0
def cut(d: deque, count: int = 0) -> None:
    if count == 0: return
    d.rotate(-count)
Exemple #21
0
def sel_loesung1(p: deque):
    inx_1 = p.index(1)
    p.rotate(-inx_1)
    p.popleft()
    return p
Exemple #22
0
def shuffle(q: deque) -> deque:
    q.pop()
    q.rotate(1)
Exemple #23
0
def spin(deque_: deque, x):
    deque_.rotate(x)
    return deque_
Exemple #24
0
async def avalon_build_quest_team(client: discord.Client,
                                  channel: discord.TextChannel, players: deque,
                                  quest_num):
    leader = players[0]
    quest_member = []
    players_id = [str(x[0].id) for x in players]
    quest_limit = [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2],
                   [2, 2, 2, 2, 2], [2, 2, 2, 2, 2], [2, 3, 2, 3, 3],
                   [2, 3, 4, 3, 4], [2, 3, 3, 4, 4], [3, 4, 4, 5, 5],
                   [3, 4, 4, 5, 5], [3, 4, 4, 5, 5]]
    cur_quest_limit = quest_limit[len(players)][quest_num]

    embed = discord.Embed(title="원정대 후보",
                          description=f"필요한 원정대 인원 : {cur_quest_limit}명",
                          colour=discord.Colour.dark_gold())
    for i in range(len(players)):
        embed.add_field(name=players[i][0].nick,
                        value=str(i + 1),
                        inline=False if i == 5 else True)

    await channel.send(
        f"현재 대표는 <@{leader[0].id}> 입니다. 원정대 {cur_quest_limit}명을 꾸려 주세요.",
        embed=embed)
    await channel.send("원정대를 선정할 때는 `!원정대 1 2`와 같이 입력합니다.")

    def check(message):
        if message.author.id == leader[0].id and (
                message.content.startswith("!출발")
                or message.content.startswith("!원정대")
        ) and message.channel == channel:
            return True
        return False

    while 1:

        valid = True
        message = await client.wait_for("message", check=check)
        message_content = message.content
        await message.delete()
        if message_content.startswith("!원정대"):
            quest_member = []
            if len(message_content.split(" ")) - 1 != cur_quest_limit:
                await channel.send(
                    f"입력하신 원정대 구성원 수`({len(message_content.split(' '))-1})`와 현재 구성해야하는 원정대 구성원 수`({cur_quest_limit})`가 맞지 않습니다."
                )
                continue
            user_input_possibility = [
                str(x) for x in range(1,
                                      len(players) + 1)
            ]
            for user_number_in_str in message_content.split(" ")[1:]:
                if user_number_in_str not in user_input_possibility:
                    await channel.send(
                        f"입력하신 문자 `({user_number_in_str})`가 후보 번호에 있지 않습니다. 정확히 입력해주세요. ex)`!원정대 1 2`"
                    )
                    valid = False
                    break
                quest_member.append(
                    str(players[int(user_number_in_str) - 1][0].id))
            if not valid:
                continue

            embed = discord.Embed(title=f"원정대 구성원 ({quest_num+1}차 원정)",
                                  colour=discord.Colour.dark_gold())
            for i in range(len(quest_member)):
                embed.add_field(name=f"원정대 {i+1}",
                                value=f"<@{quest_member[i]}>")

            await channel.send(f"원정대를 꾸렸습니다. 표결을 진행하려면 `!출발`을 입력해주세요.",
                               embed=embed)
            continue
        if message_content.startswith("!출발"):

            if len(quest_member) != cur_quest_limit:
                await channel.send(
                    f"원정에 떠나기 위한 구성원의 수`({cur_quest_limit})`와 현재 구성원의 수`({len(quest_member)})`가 다릅니다."
                )
                continue
            else:
                break
    players.rotate(-1)
    return quest_member