Skip to content

Instantly share code, notes, and snippets.

@textbook
Last active Aug 29, 2015
Embed
What would you like to do?
import datetime
from operator import itemgetter
def get_int_input(prompt, min_=0, max_=None):
"""Get a valid integer input."""
while True:
try:
i = int(input(prompt))
except ValueError:
print("Please enter an integer.")
else:
if min_ is not None and i < min_:
print("Must be at least {0}.".format(min_))
continue
elif max_ is not None and i > max_:
print("Must be at most {0}.".format(max_))
continue
return i
def get_time():
""""Get a time input as a datetime.time object."""
h = get_int_input("Hours (0-23): ", max_=23)
m = get_int_input("Minutes (0-59): ", max_=59)
s = get_int_input("Seconds (0-59): ", max_=59)
ms = get_int_input("Milliseconds (0-999): ", max_=999)
return datetime.time(h, m, s, ms*1000)
def get_results(competitors):
"""Get a dict of finishing times for all competitors."""
results = {}
for _ in range(competitors):
while True:
competitor = get_int_input("Enter competitor number: ", min_=1,
max_=competitors+1)
if competitor not in results:
results[competitor] = get_time()
break
print("Time already entered.")
return results
def print_results(results):
"""Display the race results in a table, fastest first."""
line = "-" * 32
print(line)
print("| Competitor | Time (H:M:S) |")
for n, t in sorted(results.items(), key=itemgetter(1)):
print(line)
print("| {0:<10d} | {1!s:<15} |".format(n, t))
print(line)
def race():
"""Handle race times for a user-specified number of competitors."""
n = get_int_input("Enter number of competitors (2-): ", min_=2)
results = get_results(n)
print_results(results)
if __name__ == "__main__":
race()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment