Skip to content

Commit 1e0b33d

Browse files
SandersLincclauss
authored andcommitted
Update 3n+1.py (TheAlgorithms#996)
* Update 3n+1.py Made variable names more meaningful and removed nested functions. * Update 3n+1.py * Update 3n+1.py * Update 3n+1.py
1 parent 1dc9ec8 commit 1e0b33d

File tree

1 file changed

+26
-15
lines changed

1 file changed

+26
-15
lines changed

maths/3n+1.py

+26-15
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
1-
def main():
2-
def n31(a):# a = initial number
3-
c = 0
4-
l = [a]
5-
while a != 1:
6-
if a % 2 == 0:#if even divide it by 2
7-
a = a // 2
8-
elif a % 2 == 1:#if odd 3n+1
9-
a = 3*a +1
10-
c += 1#counter
11-
l += [a]
1+
from typing import Tuple, List
2+
3+
def n31(a: int) -> Tuple[List[int], int]:
4+
"""
5+
Returns the Collatz sequence and its length of any postiver integer.
6+
>>> n31(4)
7+
([4, 2, 1], 3)
8+
"""
129

13-
return l , c
14-
print(n31(43))
15-
print(n31(98)[0][-1])# = a
16-
print("It took {0} steps.".format(n31(13)[1]))#optional finish
10+
if not isinstance(a, int):
11+
raise TypeError('Must be int, not {0}'.format(type(a).__name__))
12+
if a < 1:
13+
raise ValueError('Given integer must be greater than 1, not {0}'.format(a))
14+
15+
path = [a]
16+
while a != 1:
17+
if a % 2 == 0:
18+
a = a // 2
19+
else:
20+
a = 3*a +1
21+
path += [a]
22+
return path, len(path)
23+
24+
def main():
25+
num = 4
26+
path , length = n31(num)
27+
print("The Collatz sequence of {0} took {1} steps. \nPath: {2}".format(num,length, path))
1728

1829
if __name__ == '__main__':
1930
main()

0 commit comments

Comments
 (0)