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

Function josephus_recursive

maths/josephus_problem.py:18–77  ·  view source on GitHub ↗

Solve the Josephus problem for num_people and a step_size recursively. Args: num_people: A positive integer representing the number of people. step_size: A positive integer representing the step size for elimination. Returns: The position of the last person rem

(num_people: int, step_size: int)

Source from the content-addressed store, hash-verified

16
17
18def josephus_recursive(num_people: int, step_size: int) -> int:
19 """
20 Solve the Josephus problem for num_people and a step_size recursively.
21
22 Args:
23 num_people: A positive integer representing the number of people.
24 step_size: A positive integer representing the step size for elimination.
25
26 Returns:
27 The position of the last person remaining.
28
29 Raises:
30 ValueError: If num_people or step_size is not a positive integer.
31
32 Examples:
33 >>> josephus_recursive(7, 3)
34 3
35 >>> josephus_recursive(10, 2)
36 4
37 >>> josephus_recursive(0, 2)
38 Traceback (most recent call last):
39 ...
40 ValueError: num_people or step_size is not a positive integer.
41 >>> josephus_recursive(1.9, 2)
42 Traceback (most recent call last):
43 ...
44 ValueError: num_people or step_size is not a positive integer.
45 >>> josephus_recursive(-2, 2)
46 Traceback (most recent call last):
47 ...
48 ValueError: num_people or step_size is not a positive integer.
49 >>> josephus_recursive(7, 0)
50 Traceback (most recent call last):
51 ...
52 ValueError: num_people or step_size is not a positive integer.
53 >>> josephus_recursive(7, -2)
54 Traceback (most recent call last):
55 ...
56 ValueError: num_people or step_size is not a positive integer.
57 >>> josephus_recursive(1_000, 0.01)
58 Traceback (most recent call last):
59 ...
60 ValueError: num_people or step_size is not a positive integer.
61 >>> josephus_recursive("cat", "dog")
62 Traceback (most recent call last):
63 ...
64 ValueError: num_people or step_size is not a positive integer.
65 """
66 if (
67 not isinstance(num_people, int)
68 or not isinstance(step_size, int)
69 or num_people <= 0
70 or step_size <= 0
71 ):
72 raise ValueError("num_people or step_size is not a positive integer.")
73
74 if num_people == 1:
75 return 0

Callers 1

find_winnerFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected