بتل کد Battle Codeدارد باز می‌شود…

جواب «Time to Detect» چالش 5 از جلسه‌ی 70

سؤال

خطِ زمان را از log بساز و مرتب کن. «اولین نشانه» اولین رخدادی است که fail در آن است و «کشف» اولین رخدادی که friend asks در آن است. هر دو را به شکلِ first indicator: 09:14 و detected: 09:35 چاپ کن، و در خطِ آخر فاصله‌شان را به دقیقه: time to detect: 21 min.

راهنما

زمان را با h, m = time.split(":") به دقیقه تبدیل کن: int(h) * 60 + int(m). برای «اولین»، از حلقه‌ای که با break می‌ایستد یا از یک شرطِ is None استفاده کن.

یک جواب درست

log = '''
09:20 login ok sara unknown-pc
09:14 login fail sara unknown-pc
09:21 message sent to 40 friends
09:16 login fail sara unknown-pc
09:35 friend asks: was this you?
09:40 password changed, all devices signed out
'''

def minutes(time):
    h, m = time.split(":")
    return int(h) * 60 + int(m)

timeline = []
for line in log.strip().split("\n"):
    time, event = line.split(" ", 1)
    timeline.append((time, event))
timeline.sort()
first = None
detected = None
for time, event in timeline:
    if first is None and "fail" in event:
        first = time
    if detected is None and "friend asks" in event:
        detected = time
print("first indicator:", first)
print("detected:", detected)
print("time to detect:", minutes(detected) - minutes(first), "min")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن