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

Function partition

dynamic_programming/integer_partition.py:11–44  ·  view source on GitHub ↗

>>> partition(5) 7 >>> partition(7) 15 >>> partition(100) 190569292 >>> partition(1_000) 24061467864032622473692149727991 >>> partition(-7) Traceback (most recent call last): ... IndexError: list index out of range >>> partition(0) Traceba

(m: int)

Source from the content-addressed store, hash-verified

9
10
11def partition(m: int) -> int:
12 """
13 >>> partition(5)
14 7
15 >>> partition(7)
16 15
17 >>> partition(100)
18 190569292
19 >>> partition(1_000)
20 24061467864032622473692149727991
21 >>> partition(-7)
22 Traceback (most recent call last):
23 ...
24 IndexError: list index out of range
25 >>> partition(0)
26 Traceback (most recent call last):
27 ...
28 IndexError: list assignment index out of range
29 >>> partition(7.8)
30 Traceback (most recent call last):
31 ...
32 TypeError: 'float' object cannot be interpreted as an integer
33 """
34 memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)]
35 for i in range(m + 1):
36 memo[i][0] = 1
37
38 for n in range(m + 1):
39 for k in range(1, m):
40 memo[n][k] += memo[n][k - 1]
41 if n - k > 0:
42 memo[n][k] += memo[n - k - 1][k]
43
44 return memo[m][m - 1]
45
46
47if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected