File tree Expand file tree Collapse file tree 1 file changed +26
-15
lines changed
Expand file tree Collapse file tree 1 file changed +26
-15
lines changed Original file line number Diff line number Diff line change 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. \n Path: {2}" .format (num ,length , path ))
1728
1829if __name__ == '__main__' :
1930 main ()
You can’t perform that action at this time.
0 commit comments