Solve the Josephus problem for num_people and a step_size iteratively. Args: num_people (int): The number of people in the circle. step_size (int): The number of steps to take before eliminating someone. Returns: int: The position of the last person standing.
(num_people: int, step_size: int)
| 98 | |
| 99 | |
| 100 | def josephus_iterative(num_people: int, step_size: int) -> int: |
| 101 | """ |
| 102 | Solve the Josephus problem for num_people and a step_size iteratively. |
| 103 | |
| 104 | Args: |
| 105 | num_people (int): The number of people in the circle. |
| 106 | step_size (int): The number of steps to take before eliminating someone. |
| 107 | |
| 108 | Returns: |
| 109 | int: The position of the last person standing. |
| 110 | |
| 111 | Examples: |
| 112 | >>> josephus_iterative(5, 2) |
| 113 | 3 |
| 114 | >>> josephus_iterative(7, 3) |
| 115 | 4 |
| 116 | """ |
| 117 | circle = list(range(1, num_people + 1)) |
| 118 | current = 0 |
| 119 | |
| 120 | while len(circle) > 1: |
| 121 | current = (current + step_size - 1) % len(circle) |
| 122 | circle.pop(current) |
| 123 | |
| 124 | return circle[0] |
| 125 | |
| 126 | |
| 127 | if __name__ == "__main__": |