Making a collatz program automate the boring stuff

前端 未结 25 2275
一整个雨季
一整个雨季 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:35

    You can simply try this

    while True:
     number=int(input('Enter next positive number or 0 to quit: '))
     iteration=0
     currentNumber=0
     item=1
     sumOfNumbers=0
     print(number,end='  ')
     if(number):
        while currentNumber !=1 :
            currentNumber=int(number/2) if(number%2==0) else number*3+1
            number=currentNumber
            iteration +=1; item +=1
            sumOfNumbers +=currentNumber
            print(currentNumber,end ='\n' if(item %5==0) else '  ')
        print('\nIt took ',iteration,'iterations to arrive at 1')
        print('The average  is ',round((sumOfNumbers/iteration),2))
     else :
        break
    

提交回复
热议问题