注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 匿名 于 2026-4-20 20:32 编辑
20分鐘討論: add comment to articles
30分鐘OOD:
1. 找bug: missing float
2. 完成count_journeys
3. 完成catch_speeders
最後一道來不及寫完 求加米
class LogEntry:
def init(self, log_line):
tokens = log_line.split(' ')
# BUG WAS HERE: was tokens[0] stored as string
# Fix: use float() to parse timestamp as number
# Without this, timestamp subtraction returns NaN
# causing catchSpeeders() to never detect speeders
self.timestamp = float(tokens[0])
self.license_plate = tokens[1]
self.booth_type = tokens[3]
location_str = tokens[2]
self.location = int(location_str[:-1])
direction_letter = location_str[-1]
if direction_letter == 'E':
self.direction = 'EAST'
elif direction_letter == 'W':
self.direction = 'WEST'
else:
raise ValueError('Invalid direction letter')
def str(self):
return (f"<LogEntry timestamp: {self.timestamp} license: {self.license_plate} "
f"location: {self.location} direction: {self.direction} "
f"booth type: {self.booth_type}>")
class LogFile:
def init(self, file_contents):
self.log_entries = []
lines = file_contents.split('\n')
for line in lines:
if line.strip():
log_entry = LogEntry(line.strip())
self.log_entries.append(log_entry)
@property
def length(self):
return len(self.log_entries)
def item(self, index):
return self.log_entries[index]
def count_journeys(self):
"""
TODO: Write a function named count_journeys() that returns
how many complete journeys there are in the given LogFile.
A complete journey consists of:
- A driver entering the highway through an ENTRY MAINROAD
91874.493 JOX304 280E EXIT
91982.102 THX138 290E EXIT
92301.302 THX138 300E ENTRY
92371.302 THX138 310E EXIT"""
lf = LogFile(sample_log)
assert lf.count_journeys() == 3, f"Expected 3, got {lf.count_journeys()}"
print("test_count_journeys: OK")
def test_catch_speeders():
# TST002: 10km in 275 sec => ~130.91 km/h (speeder, 1 journey)
# TST003: two segments both >= 120 km/h (speeder, 2 journeys)
sample_log = """1000.000 TST002 270W ENTRY
1275.000 TST002 260W EXIT
2000.000 TST003 270W ENTRY
2300.000 TST003 260W MAINROAD
2601.000 TST003 250W EXIT
5000.000 TST003 270W ENTRY
5301.000 TST003 260W MAINROAD
5602.000 TST003 250W EXIT"""
lf = LogFile(sample_log)
ticket_list = lf.catch_speeders()
assert len([t for t in ticket_list if t == 'TST002']) == 1
assert len([t for t in ticket_list if t == 'TST003']) == 2
assert len(set(ticket_list)) == 2
print("test_catch_speeders: OK")
if name == 'main':
test_log_entry()
test_count_journeys()
test_catch_speeders()
print("\nAll tests passed!")
|