Skip to content

Commit e7ab06f

Browse files
echoajpoyea
andauthored
Implemented minimum steps to one using tabulation. (#3911)
* Implemented minimum steps to one using tabulation. * Update minimum_steps_to_one.py Made the parameter "n" more descriptive. Changed it to number * `n` to `number` Co-authored-by: John Law <[email protected]>
1 parent c39be1d commit e7ab06f

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Diff for: dynamic_programming/minimum_steps_to_one.py

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
YouTube Explanation: https://www.youtube.com/watch?v=f2xi3c1S95M
3+
4+
Given an integer n, return the minimum steps to 1
5+
6+
AVAILABLE STEPS:
7+
* Decrement by 1
8+
* if n is divisible by 2, divide by 2
9+
* if n is divisible by 3, divide by 3
10+
11+
12+
Example 1: n = 10
13+
10 -> 9 -> 3 -> 1
14+
Result: 3 steps
15+
16+
Example 2: n = 15
17+
15 -> 5 -> 4 -> 2 -> 1
18+
Result: 4 steps
19+
20+
Example 3: n = 6
21+
6 -> 2 -> 1
22+
Result: 2 step
23+
"""
24+
25+
from __future__ import annotations
26+
27+
__author__ = "Alexander Joslin"
28+
29+
30+
def min_steps_to_one(number: int) -> int:
31+
"""
32+
Minimum steps to 1 implemented using tabulation.
33+
>>> min_steps_to_one(10)
34+
3
35+
>>> min_steps_to_one(15)
36+
4
37+
>>> min_steps_to_one(6)
38+
2
39+
40+
:param number:
41+
:return int:
42+
"""
43+
44+
if number <= 0:
45+
raise ValueError(f"n must be greater than 0. Got n = {number}")
46+
47+
table = [number + 1] * (number + 1)
48+
49+
# starting position
50+
table[1] = 0
51+
for i in range(1, number):
52+
table[i + 1] = min(table[i + 1], table[i] + 1)
53+
# check if out of bounds
54+
if i * 2 <= number:
55+
table[i * 2] = min(table[i * 2], table[i] + 1)
56+
# check if out of bounds
57+
if i * 3 <= number:
58+
table[i * 3] = min(table[i * 3], table[i] + 1)
59+
return table[number]
60+
61+
62+
if __name__ == "__main__":
63+
import doctest
64+
65+
doctest.testmod()

0 commit comments

Comments
 (0)