Skip to content

Instantly share code, notes, and snippets.

@cpyle0819
Created February 1, 2024 16:40
Show Gist options
  • Save cpyle0819/f6031c04ae2bdd45b37ddf6bd2b71e20 to your computer and use it in GitHub Desktop.
Save cpyle0819/f6031c04ae2bdd45b37ddf6bd2b71e20 to your computer and use it in GitHub Desktop.
Generate N user action records.
from dataclasses import dataclass, asdict
from random import randint
from typing import Literal, Dict, List
from faker import Faker
@dataclass
class Record:
user_name: str
action: Literal["view", "search", "purchase"]
def records_empty(records: Dict[str, List[Record]]):
for record_list in records.values():
if len(record_list) > 0:
return False
return True
def make_records(record_count: int, user_count: int):
fake = Faker()
user_records = {}
browse_actions = ["view", "search"]
purchase_action = "purchase"
users = [fake.name() for i in range(user_count)]
record_list = []
for i in range(record_count):
user_name = users[randint(0, 2)]
if user_name not in user_records:
user_records[user_name] = []
action = (
purchase_action
if len(user_records[user_name]) > 0
and randint(1, 100) > 75
and user_records[user_name][-1].action == "view"
else browse_actions[randint(0, 1)]
)
new_record = Record(user_name=user_name, action=action)
user_records[user_name].append(new_record)
while records_empty(user_records) is not True:
user = users[randint(0, len(users) - 1)]
user_record_list = user_records[user] if user in user_records else []
if user_record_list:
record_list.append(user_record_list.pop(0))
print([asdict(r) for r in record_list])
if __name__ == "__main__":
make_records(record_count=100, user_count=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment