Advertisement
acclivity

pyCollatz

Aug 9th, 2021
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. # collatz Python exercise
  2. # Mike Kerry Dec 2020
  3.  
  4. def collatz(number):
  5.     if not number & 1:          # bit-wise test for even
  6.         return number >> 1      # >> 1 integer divides by 2
  7.     return 3 * number + 1       # number was odd
  8.  
  9.  
  10. while True:
  11.     mystr = input("Type a number: ")    # input as a string
  12.     if mystr.isdigit():                 # if the input is an integer ...
  13.         break                           # break out of while loop
  14.     print("Invalid number, try again")  # report invalid input and loop again
  15.  
  16. y = int(mystr)              # convert input string to an integer
  17. while y != 1:               # Keep looping until y is 1
  18.     y = collatz(y)          # pass y to the function, and assign the return value to y
  19.     print(y)                # print y each time around loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement