-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhorses.py
More file actions
57 lines (39 loc) · 1.43 KB
/
horses.py
File metadata and controls
57 lines (39 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import random
class Horse:
def __init__(self, speed) -> None:
self.speed = speed
class RaceTrack:
size = 5
def race(cls, horses):
if len(horses) > cls.size:
raise ValueError(f"Cannot race more than {cls.size} horses")
horses.sort(key=lambda h: h.speed, reverse=True)
def cull(cls, horses: list[Horse]):
while len(horses) > 3:
horses.pop()
horses = {Horse(speed=random.random() * 100) for _ in range(25)}
actual_top_3 = sorted(horses, key=lambda h: h.speed, reverse=True)[:3]
sorted_batches = []
reference_horse = None
current = None
while horses:
if not current:
batch = [horses.pop() for _ in range(RaceTrack.size)]
else:
reference_horse = current[-1]
batch = [reference_horse] + [horses.pop() for _ in range(RaceTrack.size - 1)]
RaceTrack.race(batch)
RaceTrack.cull(batch)
# We know that there are two horses faster than this one,
# so if any horse is slower than the reference, they're out.
if reference_horse in batch:
batch = batch[batch.index(reference_horse) + 1 :]
if batch:
sorted_batches.append(batch)
assert len(sorted_batches) <= 5
by_fastest_horse = {batch[0]: batch for batch in sorted_batches}
sorted_fastest = RaceTrack.race(by_fastest_horse.keys())
survivors = RaceTrack.cull(sorted_fastest)
by_fastest_horse = {
batch[0]: batch for batch in sorted_batches if batch[0] in survivors
}