Making a collatz program automate the boring stuff

前端 未结 25 2342
一整个雨季
一整个雨季 2020-12-08 11:14

I\'m trying to write a Collatz program using the guidelines from a project found at the end of chapter 3 of Automate the Boring Stuff with Python. I\'m using python 3.

25条回答
  •  余生分开走
    2020-12-08 11:36

    i am reading the same course and i made a very long solution (improving it when i learn somethign new). i suggest keeping your collatz program up to date as you progress in the chapters, its good training. mine has string manipulation and saving to a \collatzrecords.txt now!

    I solved the core problem by using recursion (a method calls itself):

    def autocollatz(number):
    global spam                     
    spam.append(number)             
    if number % 2 == 0:             
        autocollatz (int(number/2))
    elif number % 2 == 1 and number != 1:
        autocollatz(int(number*3+1))
    

    spam is my list for all the values a number "sees" on its way to 1. as you can see, when the number is even the ethod is called agin with number/2. if the number is even it is called with number*3+1.

    modified the number == 1 check a bit. i hope it saves calculating time - im up to 23 000 000 already! (current record is 15 733 191 with 704 steps to get it to 1)

提交回复
热议问题