Skip to content

Instantly share code, notes, and snippets.

@yarko
Created August 8, 2017 06:27
Show Gist options
  • Save yarko/403d5c3c06946638fb637ef837cd8060 to your computer and use it in GitHub Desktop.
Save yarko/403d5c3c06946638fb637ef837cd8060 to your computer and use it in GitHub Desktop.
#!/bin/env python
# doing little more than applying my suggestions to the
# first-time coding effort of:
# https://www.reddit.com/r/Python/comments/6rvd0v/first_time_properly_getting_into_coding_how_is/
# There is more which can be done / said here (e.g. EOF-quit handling), but this
# shows the suggestions I put forth applied, and the effect of separating getting input
# from forming the calculation.
import sys
def get_integer(prompt=None):
quitters = ('q', 's')
quitting = lambda s: s.lower().startswith(quitters)
if prompt is None:
prompt = "Value to test compliance with Colatz Conjecture: "
err_prompt = 'Enter an integer greater than zero, or "quit"'
while True:
s = input(prompt)
if quitting(s):
sys.exit(0)
try:
i = int(s)
except:
print(err_prompt)
continue
if i > 0:
yield i
else:
print(err_prompt)
x = 0
even = lambda x: x%2==0
for x in get_integer():
print(f'in: {x}')
i = 0 # number of calculations
while x != 1:
x = x//2 if even(x) else 3*x+1
i += 1
print(f'out: {x}, {i}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment