Advertisement
B1KMusic

collatz.py improved (v1.1.2)

Aug 9th, 2016
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # For both Python 2.x and 3.x
  3. """
  4. Changelog:
  5. v1.1.0
  6.    + added get_version() for compatibility with python 2 and 3
  7.    + added perror() for non-fatal errors
  8.    + added get_input() to choose the correct input function for python 2/3
  9. v1.1.1
  10.    + added safe_int() to guarantee that a number is returned
  11. v1.1.2
  12.    + handles Ctrl+C (interrupt).
  13. """
  14.  
  15. import sys
  16.  
  17. def collatz_calc(n):
  18.     if n % 2 == 0:
  19.         return n / 2
  20.     else:
  21.         return n * 3 + 1
  22.  
  23. def collatz_reduce(n):
  24.     steps = 0
  25.     n_cpy = n
  26.  
  27.     while n > 1:
  28.         print(n)
  29.         n = int(collatz_calc(n))
  30.         steps += 1
  31.  
  32.     print("%u reduced to 1 in %u steps" % (n_cpy, steps))
  33.  
  34. def die(msg = "", code = 0):
  35.     perror(msg)
  36.     sys.exit(code)
  37.  
  38. def get_choice():
  39.     try:
  40.         choice = get_input("Enter a number (q to exit): ")
  41.     except (EOFError, KeyboardInterrupt):
  42.         die("\n")
  43.  
  44.     if choice == "q":
  45.         die()
  46.     else:
  47.         return safe_int(choice)
  48.  
  49. def get_input(msg = ""):
  50.     version = get_version()
  51.  
  52.     if version[0] == "2":
  53.         return raw_input(msg)
  54.     elif version[0] == "3":
  55.         return input(msg)
  56.    
  57.  
  58. def get_version():
  59.     start, end = 0, 0
  60.  
  61.     while sys.version[end] != ' ':
  62.         end += 1
  63.  
  64.     return sys.version[start:end]
  65.  
  66. def loop():
  67.     while True:
  68.         n = get_choice()
  69.  
  70.         if n <= 0:
  71.             perror("Error: Bad input\n")
  72.             continue
  73.  
  74.         collatz_reduce(n)
  75.  
  76. def perror(msg):
  77.     sys.stderr.write(msg)
  78.  
  79. def safe_int(n):
  80.     try:
  81.         return int(n)
  82.     except ValueError:
  83.         return 0
  84.  
  85. def main():
  86.     version = get_version()
  87.  
  88.     if not version[0] in "23":
  89.         die("Error: unknown python version '%s'\n" % version, 1)
  90.  
  91.     loop()
  92.  
  93. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement