Check if a stack is sorted in ascending order (bottom to top). Args: stack: A list representing a stack (bottom to top). Returns: True if sorted in ascending order, False otherwise. Examples: >>> is_sorted([1, 2, 3, 4, 5, 6]) True >>> is_sorted(
(stack: list[int])
| 15 | |
| 16 | |
| 17 | def is_sorted(stack: list[int]) -> bool: |
| 18 | """Check if a stack is sorted in ascending order (bottom to top). |
| 19 | |
| 20 | Args: |
| 21 | stack: A list representing a stack (bottom to top). |
| 22 | |
| 23 | Returns: |
| 24 | True if sorted in ascending order, False otherwise. |
| 25 | |
| 26 | Examples: |
| 27 | >>> is_sorted([1, 2, 3, 4, 5, 6]) |
| 28 | True |
| 29 | >>> is_sorted([6, 3, 5, 1, 2, 4]) |
| 30 | False |
| 31 | """ |
| 32 | storage_stack: list[int] = [] |
| 33 | for _ in range(len(stack)): |
| 34 | if len(stack) == 0: |
| 35 | break |
| 36 | first_val = stack.pop() |
| 37 | if len(stack) == 0: |
| 38 | break |
| 39 | second_val = stack.pop() |
| 40 | if first_val < second_val: |
| 41 | return False |
| 42 | storage_stack.append(first_val) |
| 43 | stack.append(second_val) |
| 44 | |
| 45 | for _ in range(len(storage_stack)): |
| 46 | stack.append(storage_stack.pop()) |
| 47 | |
| 48 | return True |