MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / josephus_iterative

Function josephus_iterative

maths/josephus_problem.py:100–124  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

98
99
100def 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
127if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

popMethod · 0.45

Tested by

no test coverage detected