MCPcopy
hub / github.com/keon/algorithms / first_switch_pairs

Function first_switch_pairs

algorithms/stack/switch_pairs.py:20–46  ·  view source on GitHub ↗

Switch successive pairs using an auxiliary stack. Args: stack: A list representing a stack (bottom to top). Returns: The stack with successive pairs swapped. Examples: >>> first_switch_pairs([3, 8, 17, 9, 1, 10]) [8, 3, 9, 17, 10, 1]

(stack: list[int])

Source from the content-addressed store, hash-verified

18
19
20def first_switch_pairs(stack: list[int]) -> list[int]:
21 """Switch successive pairs using an auxiliary stack.
22
23 Args:
24 stack: A list representing a stack (bottom to top).
25
26 Returns:
27 The stack with successive pairs swapped.
28
29 Examples:
30 >>> first_switch_pairs([3, 8, 17, 9, 1, 10])
31 [8, 3, 9, 17, 10, 1]
32 """
33 storage_stack: list[int] = []
34 for _ in range(len(stack)):
35 storage_stack.append(stack.pop())
36 for _ in range(len(storage_stack)):
37 if len(storage_stack) == 0:
38 break
39 first = storage_stack.pop()
40 if len(storage_stack) == 0:
41 stack.append(first)
42 break
43 second = storage_stack.pop()
44 stack.append(second)
45 stack.append(first)
46 return stack
47
48
49def second_switch_pairs(stack: list[int]) -> list[int]:

Callers 1

test_switch_pairsMethod · 0.90

Calls 1

popMethod · 0.45

Tested by 1

test_switch_pairsMethod · 0.72