可以在每個時間間隔存儲爲一對相應於時間間隔的開始/結束的整數:
from collections import namedtuple
Interval = namedtuple('Interval', 'start end')
如果有這樣的字符串作爲'10-13'
;你可以將其轉換爲Interval
:
user_hours = Interval(*map(int, '10-13'.split('-')))
# -> Interval(start=10, end=13)
要找出「什麼動物都可以顯示在該時間間隔」,你需要知道兩個給定的時間間隔是否相交:
def intersect(a, b):
return a.start < b.end and b.start < a.end
示例:
>>> intersect(Interval(8,18), Interval(10,13))
True
沒有隔夜間隔,因此您可以將時間間隔視爲線性(線上的間隔)。
現在,你只需要與來訪的時間來填充表爲動物園的動物:
visiting_hours = {
"bear": Interval(8, 18), # 08-18
"lion": Interval(14, 16), # 14-16
}
,你也可以打印出的動物可用於給定用戶時間:
for animal, available_hours in visiting_hours:
if intersect(user_hours, available_hours):
print(animal)
作爲一種替代方案,您可以使用datetime.time()
而不是int
來表示小時 - 它會自動強制使用有效值(0..23)幾小時:
from datetime import datetime
while True:
user_input = input("Input time interval e.g., 10-13: ")
try:
user_hours = Interval(*[datetime.strptime(h, "%H").time()
for h in user_input.split('-')])
except ValueError as e:
print("Invalid input: %s. Try again." % (e,))
else:
break
相應修改「探視時間」表:
from datetime import time
visiting_hours = {
"bear": Interval(time(8), time(18)),
"lion": Interval(time(14), time(16)),
}
您可以通過從文件中讀取的探視時間例如自動輸入。
其餘代碼保持不變。
您可以在探視時間保存到一個單獨的文件,例如,SQLite數據庫和獨立編輯表(使用其他腳本):
:
#!/usr/bin/env python
import sqlite3
db = sqlite3.connect(':memory:') # create in memory for debugging
db.execute('''CREATE TABLE intervals
(animal text, start integer, end integer)''')
# populate
visiting_hours = [('bear', '08-18'), ('lion', '14-16')]
db.executemany('INSERT INTO intervals VALUES (?, ?, ?)',
[[animal] + list(map(int, hours.split('-')))
for animal, hours in visiting_hours])
爲了從數據庫中獲取的動物
# "what animals are available for show at that time interval"
for animal, in db.execute('''SELECT animal FROM intervals
WHERE ? < end and start < ?''',
tuple(map(int, '10-13'.split('-')))):
print(animal)
如果你問「如何取一個包含'」06-08「的變量'a',並得到兩個變量'b'和'c'包含'」06「和」「08 「'分別?」:'b,c = a.split(「 - 」)' – Kevin
什麼你到目前爲止嘗試過嗎?您可能需要將每個字符串轉換爲整數,開始時間和結束時間。 – DJMcMayhem