top of page

In honor of Lothar Collatz


In 1937, a German mathematician named Lothar Collatz formulated an intriguing hypothesis (it still remains unproven) which can be described in the following way:

  1. take any non-negative and non-zero integer number and name it c0;

  2. if it's even, evaluate a new c0 as c0 ÷ 2;

  3. otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1;

  4. if c0 ≠ 1, skip to point 2.

The hypothesis says that regardless of the initial value of c0, it will always go to 1.

 

My code:

def collatz(c0): count = 0 while c0 != 1: count += 1 if c0 % 2 == 0: c0 = c0 // 2 elif c0 % 2 == 1: c0 = c0*3 + 1 print(c0) else: print("steps = ", count) collatz(int(input('type any non-negative and non-zero integer number: ')))

It is important that the indentations in the code must be right!

 

Test Data

 

Sample input: 15 Expected output: 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 steps = 17

 

Sample input: 16 Expected output: 8 4 2 1 steps = 4

 

Sample input: 1023 Expected output: 3070 1535 4606 2303 6910 3455 10366 5183 15550 7775 23326 11663 34990 17495 52486 26243 78730 39365 118096 59048 29524 14762 7381 22144 11072 5536 2768 1384 692 346 173 520 260 130 65 196 98 49 148 74 37 112 56 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 steps = 62

 

Two related knowledge of python:

 

aboutME

I am John Fan Zhang, a data analyst and finance researcher. I hold a PhD in finance, CFA charter and full membership of CFA New Zealand Society. I have fifteen-year experience in corporate investment and eight-year experience in advanced data analysis. My research focuses on the effect of social psychology (culture) on financial decisions. Finance research involves heaps of data analyses that lead me to the data field. I am a Microsoft Certified Solutions Expert (MCSE): Data Management and Analytics (Excel, Power BI, and SQL). Aside from Excel, Power BI and SQL, I am also familiar with econometric tools such as Stata, Eviews, and MATLAB. I use OX and Python for programming. I am an active data community event participant, volunteer, speaker, moderator, program reviewer, including PASS Marathon 2020, Global AI BootCamp Auckland 2019, SQL Saturday Auckland (2017, 2018, 2019), and Definity Conference (2018, 2019, 2020, Auckland, New Zealand).

Auckland, New Zealand

  • Google Site
  • Twitter
  • LinkedIn

©2016 BY JOHN'S DATA STORY

bottom of page