Ini akan berjalan dalam python (hanya 3.X, bukan 2.7), bebas untuk menginstal bahasa pemrograman. Cukup simpan yang berikut ini sebagai akhiran file .py
- mis timetrials.py
. Kemudian buka IDLE3 (menu mulai), dan buka file ( Ctrl+ O). Akhirnya, tekan F5untuk memulainya.
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.")
print_results(results)
return results
def print_results(results):
"""Display the race results in a table, fastest first."""
linet = '┌' + "─" * 12 + '┬' + '─' * 17 + '┐'
linec = '├' + "─" * 12 + '┼' + '─' * 17 + '┤'
lineb = '└' + "─" * 12 + '┴' + '─' * 17 + '┘'
print(linet)
print("│ Competitor │ Time (H:M:S) │")
for n, t in sorted(results.items(), key=itemgetter(1)):
print(linec)
print("│ {0:<10d} │ {1!s:<15} │".format(n, t))
print(lineb)
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)
if __name__ == "__main__":
race()
Ketika semua orang selesai, itu akan terlihat seperti ini:
┌──────────────┬───────────────┐
│ Con Num │ Time H:M:S │
├──────────────┼───────────────┤
│ 1 │ 5:4:3.2 │
├──────────────┼───────────────┤
│ 2 │ 8:7:6.5 │
├──────────────┼───────────────┤
│ 3 │ 2:2:2.2 │
└──────────────┴───────────────┘