Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # For both Python 2.x and 3.x
- """
- Changelog:
- v1.1.0
- + added get_version() for compatibility with python 2 and 3
- + added perror() for non-fatal errors
- + added get_input() to choose the correct input function for python 2/3
- v1.1.1
- + added safe_int() to guarantee that a number is returned
- v1.1.2
- + handles Ctrl+C (interrupt).
- """
- import sys
- def collatz_calc(n):
- if n % 2 == 0:
- return n / 2
- else:
- return n * 3 + 1
- def collatz_reduce(n):
- steps = 0
- n_cpy = n
- while n > 1:
- print(n)
- n = int(collatz_calc(n))
- steps += 1
- print("%u reduced to 1 in %u steps" % (n_cpy, steps))
- def die(msg = "", code = 0):
- perror(msg)
- sys.exit(code)
- def get_choice():
- try:
- choice = get_input("Enter a number (q to exit): ")
- except (EOFError, KeyboardInterrupt):
- die("\n")
- if choice == "q":
- die()
- else:
- return safe_int(choice)
- def get_input(msg = ""):
- version = get_version()
- if version[0] == "2":
- return raw_input(msg)
- elif version[0] == "3":
- return input(msg)
- def get_version():
- start, end = 0, 0
- while sys.version[end] != ' ':
- end += 1
- return sys.version[start:end]
- def loop():
- while True:
- n = get_choice()
- if n <= 0:
- perror("Error: Bad input\n")
- continue
- collatz_reduce(n)
- def perror(msg):
- sys.stderr.write(msg)
- def safe_int(n):
- try:
- return int(n)
- except ValueError:
- return 0
- def main():
- version = get_version()
- if not version[0] in "23":
- die("Error: unknown python version '%s'\n" % version, 1)
- loop()
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement