summaryrefslogtreecommitdiff
path: root/py03/ex5/ft_data_stream.py
blob: b2b0aa63e2a71be962b989adcb2b7c3e967f5f7a (plain)
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
#!/usr/bin/env python3
# https://www.geeksforgeeks.org/python/how-to-yield-values-from-list-in-python/

import random

players = ['john', 'yaya', 'elise', 'niko']
actions = ['jump', 'walk', 'run', 'swim']


def gen_event(players, actions):
    player = random.choice(players)
    action = random.choice(actions)
    yield player, action


# print 1,000 events
for event in range(1000):
    # gen_event() returns a 'generator'
    g = gen_event(players, actions)
    # create a tuple
    event_tuple = tuple(next(g))
    # unpack the tuple
    (player, action) = event_tuple
    print(f"Event {event}: Player {player} did {action}")
print()

# create a list of 10 tuples
events = []
for i in range(10):
    g = gen_event(players, actions)
    event_tuple = tuple(next(g))
    events.append(event_tuple)
print(f"Build a list of 10 events: {events}")
print()


# consume list
def consume_event(events, nb_events):
    for i in range(nb_events):
        ran = random.choice(events)
        events.remove(ran)
        yield ran


nb_events = len(events)


for event in consume_event(events, nb_events):
    print(f"Got event from list: {event}")
    print(f"Remains in list: {events}")