Advertisement
Guest User

collatz.py

a guest
Mar 7th, 2014
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. def collatz(n):
  2.     yield n
  3.     while True:
  4.         if n == 1:
  5.             return
  6.         elif not n % 2:
  7.             n = n / 2
  8.         else:
  9.             n = (3 * n) + 1
  10.         yield n
  11.         collatz(n)
  12.        
  13. def main():
  14.     while True:    
  15.         try:
  16.             n = int(raw_input("\n\nEnter a positive integer >"))
  17.         except ValueError:
  18.             print "Invalid input"
  19.         else:
  20.             break        
  21.     print ", ".join([str(x) for x in collatz(n)])
  22.        
  23. if __name__ == "__main__":
  24.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement