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

Function backtrack

backtracking/power_sum.py:10–51  ·  view source on GitHub ↗

>>> backtrack(13, 2, 1, 0, 0) (0, 1) >>> backtrack(10, 2, 1, 0, 0) (0, 1) >>> backtrack(10, 3, 1, 0, 0) (0, 0) >>> backtrack(20, 2, 1, 0, 0) (0, 1) >>> backtrack(15, 10, 1, 0, 0) (0, 0) >>> backtrack(16, 2, 1, 0, 0) (0, 1) >>> backtrack(20, 1, 1,

(
    needed_sum: int,
    power: int,
    current_number: int,
    current_sum: int,
    solutions_count: int,
)

Source from the content-addressed store, hash-verified

8
9
10def backtrack(
11 needed_sum: int,
12 power: int,
13 current_number: int,
14 current_sum: int,
15 solutions_count: int,
16) -> tuple[int, int]:
17 """
18 >>> backtrack(13, 2, 1, 0, 0)
19 (0, 1)
20 >>> backtrack(10, 2, 1, 0, 0)
21 (0, 1)
22 >>> backtrack(10, 3, 1, 0, 0)
23 (0, 0)
24 >>> backtrack(20, 2, 1, 0, 0)
25 (0, 1)
26 >>> backtrack(15, 10, 1, 0, 0)
27 (0, 0)
28 >>> backtrack(16, 2, 1, 0, 0)
29 (0, 1)
30 >>> backtrack(20, 1, 1, 0, 0)
31 (0, 64)
32 """
33 if current_sum == needed_sum:
34 # If the sum of the powers is equal to needed_sum, then we have a solution.
35 solutions_count += 1
36 return current_sum, solutions_count
37
38 i_to_n = current_number**power
39 if current_sum + i_to_n <= needed_sum:
40 # If the sum of the powers is less than needed_sum, then continue adding powers.
41 current_sum += i_to_n
42 current_sum, solutions_count = backtrack(
43 needed_sum, power, current_number + 1, current_sum, solutions_count
44 )
45 current_sum -= i_to_n
46 if i_to_n < needed_sum:
47 # If the power of i is less than needed_sum, then try with the next power.
48 current_sum, solutions_count = backtrack(
49 needed_sum, power, current_number + 1, current_sum, solutions_count
50 )
51 return current_sum, solutions_count
52
53
54def solve(needed_sum: int, power: int) -> int:

Callers 1

solveFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected