Help with python please collatzcountsn Given a positive inte
Help with python please
collatz_counts(n): Given a positive integer n, repeat the following steps until you reach 1: if we have an even number, divide it by two to get the next integer; if it is odd, triple it and add one to get the next integer. It is postulated as Collatz conjecture that we can always terminate at 1 no matter what number we start with. Suppose the initial value n is our first step, count how many halving and tripling steps it will take for us to reach the ending value 1.
Assume: n is a positive integer.
Solution
collatz_counts = {} def collatz(n): count = 1 start = n while n!=1: if n in collatz_counts: count += collatz_counts[n] break if n%2==0: n/=2 else: n = 3*n+1 count += 1 collatz_counts[start] = count return count answer = max(((collatz(i),i) for i in range(1,1000000))) print(\"The starting position generating the longest sequence is {0}\".format(answer[1]))
