forked from CodeMouse92/DeadSimplePython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraffic_generator_class.py
More file actions
42 lines (27 loc) · 866 Bytes
/
traffic_generator_class.py
File metadata and controls
42 lines (27 loc) · 866 Bytes
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
from random import choice
colors = ['red', 'green', 'blue', 'silver', 'white', 'black']
vehicles = ['car', 'truck', 'semi', 'motorcycle', None]
# as an iterator class
# class Traffic:
# def __iter__(self):
# return self
# def __next__(self):
# vehicle = choice(vehicles)
# if vehicle is None:
# raise StopIteration
# color = choice(colors)
# return f"{color} {vehicle}"
# as a generator function
def traffic():
while True:
vehicle = choice(vehicles)
if vehicle is None:
return
color = choice(colors)
yield f"{color} {vehicle}"
# merge into traffic
count = 0
# for count, vehicle in enumerate(Traffic(), start=1):
for count, vehicle in enumerate(traffic(), start=1):
print(f"Wait for {vehicle}...")
print(f"Merged after {count} vehicles!")