Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

system-design-primer #1012

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

1. User Class:

a. Represents a user of the streaming service.
b. Can create playlists and receive content recommendations based on their playlists.

2. Subscription Class:

a. Represents a user's subscription type and monthly fee.

3. Media Class:

a. Represents a media item (e.g., a movie or song) with attributes like title, genre, and play count.
b. Includes a method to play the media, which increments the play count.

4. Playlist Class:

a. Represents a user-created playlist that can hold multiple media items.
b. Includes methods to add media to the playlist and display the playlist.

5. MediaLibrary Class:

a. Manages the collection of media items available for streaming.
b. Includes methods to add media to the library and provide recommendations based on user playlists.
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
class User:
def __init__(self, user_id, name, subscription):
self.user_id = user_id
self.name = name
self.subscription = subscription
self.playlists = []

def create_playlist(self, playlist_name):
playlist = Playlist(playlist_name)
self.playlists.append(playlist)
print(f"Playlist '{playlist_name}' created for {self.name}.")

def recommend_content(self, media_library):
recommendations = media_library.get_recommendations(self)
print(f"Recommendations for {self.name}: {', '.join(recommendations)}")

class Subscription:
def __init__(self, subscription_type, monthly_fee):
self.subscription_type = subscription_type
self.monthly_fee = monthly_fee

class Media:
def __init__(self, media_id, title, genre):
self.media_id = media_id
self.title = title
self.genre = genre
self.play_count = 0

def play(self):
self.play_count += 1
print(f"Playing '{self.title}'.")

class Playlist:
def __init__(self, name):
self.name = name
self.media_items = []

def add_media(self, media):
self.media_items.append(media)
print(f"Added '{media.title}' to playlist '{self.name}'.")

def show_playlist(self):
print(f"Playlist '{self.name}': {[media.title for media in self.media_items]}")

class MediaLibrary:
def __init__(self):
self.media_collection = []

def add_media(self, media):
self.media_collection.append(media)
print(f"Media '{media.title}' added to the library.")

def get_recommendations(self, user):
# Simple recommendation based on genres of user's playlists
recommended = []
for playlist in user.playlists:
for media in playlist.media_items:
if media.genre not in recommended:
recommended.append(media.genre)

# Return a list of media titles from the library that match recommended genres
recommendations = [media.title for media in self.media_collection if media.genre in recommended]
return recommendations[:5] # Limit to 5 recommendations

# Example Usage
# Create media library and add media
media_library = MediaLibrary()
media_library.add_media(Media(1, "Inception", "Sci-Fi"))
media_library.add_media(Media(2, "Titanic", "Romance"))
media_library.add_media(Media(3, "The Matrix", "Sci-Fi"))
media_library.add_media(Media(4, "The Godfather", "Crime"))
media_library.add_media(Media(5, "Interstellar", "Sci-Fi"))

# Create a subscription
basic_subscription = Subscription("Basic", 9.99)

# Create a user
user1 = User(1, "Alice", basic_subscription)

# User creates a playlist and adds media
user1.create_playlist("Favorites")
user1.playlists[0].add_media(media_library.media_collection[0]) # Inception
user1.playlists[0].add_media(media_library.media_collection[2]) # The Matrix

# Show the user's playlist
user1.playlists[0].show_playlist()

# Get recommendations for the user
user1.recommend_content(media_library)

# Play a media item
media_library.media_collection[0].play() # Play Inception
62 changes: 62 additions & 0 deletions B4/Solutions/object_oriented_design/banking_system/banking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
class Account:
def __init__(self, account_number, account_holder, balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = balance

def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}. New balance: {self.balance}")

def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds.")
else:
self.balance -= amount
print(f"Withdrawn {amount}. New balance: {self.balance}")

def get_balance(self):
return self.balance

class Transaction:
def __init__(self, transaction_id, account, amount, transaction_type):
self.transaction_id = transaction_id
self.account = account
self.amount = amount
self.transaction_type = transaction_type

def execute(self):
if self.transaction_type == "deposit":
self.account.deposit(self.amount)
elif self.transaction_type == "withdraw":
self.account.withdraw(self.amount)
else:
print("Invalid transaction type.")

class Bank:
def __init__(self):
self.accounts = {}

def create_account(self, account_number, account_holder):
if account_number not in self.accounts:
self.accounts[account_number] = Account(account_number, account_holder)
print(f"Account created for {account_holder}.")
else:
print("Account already exists.")

def get_account(self, account_number):
return self.accounts.get(account_number, None)

# Example Usage
bank = Bank()
bank.create_account("123456", "Alice")
bank.create_account("789012", "Bob")

alice_account = bank.get_account("123456")
transaction1 = Transaction(1, alice_account, 1000, "deposit")
transaction1.execute()

transaction2 = Transaction(2, alice_account, 500, "withdraw")
transaction2.execute()

print(f"Alice's balance: {alice_account.get_balance()}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Banking System:

1. Account: Represents a bank account, with methods to deposit,
withdraw, and check the balance.

2. Transaction: Represents a transaction, which can either be a
deposit or withdrawal.

3. Bank: Manages accounts and allows for account creation.
14 changes: 14 additions & 0 deletions B4/Solutions/object_oriented_design/food_delivery/features.text
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Features of this Food Delivery System:

1. Customer Class: Represents a customer with attributes like name, address, and phone number.

2. Restaurant Class: Represents a restaurant with a menu. It allows the system to show available
items and get the price of food.

3. DeliveryPerson Class: Represents a delivery person who is assigned to deliver an order.

4. Order Class: Represents an order with details like the customer, restaurant, and the food
item ordered. It also includes the price of the order.

5. FoodDeliverySystem Class: This is the core of the system. It manages customers, restaurants,
delivery personnel, and the order placement process. It assigns a delivery person to each order.
134 changes: 134 additions & 0 deletions B4/Solutions/object_oriented_design/food_delivery/food_delivery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
class Customer:
def __init__(self, name, address, phone):
self.name = name
self.address = address
self.phone = phone

def __str__(self):
return f"Customer: {self.name}, Address: {self.address}, Phone: {self.phone}"


class Restaurant:
def __init__(self, name, menu):
self.name = name
self.menu = menu # menu is a dictionary with item names as keys and prices as values

def show_menu(self):
print(f"Menu for {self.name}:")
for item, price in self.menu.items():
print(f"{item}: ${price:.2f}")

def get_price(self, item):
return self.menu.get(item, None)

def __str__(self):
return f"Restaurant: {self.name}"


class DeliveryPerson:
def __init__(self, name):
self.name = name

def deliver(self, customer, order):
print(f"{self.name} is delivering {order.food_item} to {customer.name} at {customer.address}")

def __str__(self):
return f"Delivery Person: {self.name}"


class Order:
def __init__(self, customer, restaurant, food_item):
self.customer = customer
self.restaurant = restaurant
self.food_item = food_item
self.price = self.restaurant.get_price(food_item)

def display_order_details(self):
print(f"Order Details: \nCustomer: {self.customer.name}\nFood Item: {self.food_item}\n"
f"Price: ${self.price:.2f}\nRestaurant: {self.restaurant.name}")

def __str__(self):
return f"Order: {self.food_item} from {self.restaurant.name} for {self.customer.name}"


class FoodDeliverySystem:
def __init__(self):
self.customers = []
self.restaurants = []
self.delivery_people = []

def add_customer(self, customer):
self.customers.append(customer)

def add_restaurant(self, restaurant):
self.restaurants.append(restaurant)

def add_delivery_person(self, delivery_person):
self.delivery_people.append(delivery_person)

def place_order(self, customer, restaurant, food_item):
if food_item not in restaurant.menu:
print(f"Sorry, {food_item} is not available at {restaurant.name}.")
return None

order = Order(customer, restaurant, food_item)
order.display_order_details()
delivery_person = self.assign_delivery_person()
if delivery_person:
delivery_person.deliver(customer, order)
return order

def assign_delivery_person(self):
if not self.delivery_people:
print("No delivery person available at the moment.")
return None
# Assign the first available delivery person
return self.delivery_people[0]

def show_restaurants(self):
for restaurant in self.restaurants:
print(restaurant)

def show_customers(self):
for customer in self.customers:
print(customer)


# Example usage
if __name__ == "__main__":
# Initialize the system
delivery_system = FoodDeliverySystem()

# Create some customers
customer1 = Customer("Alice", "123 Main St", "555-1234")
customer2 = Customer("Bob", "456 Oak St", "555-5678")

# Add customers to the system
delivery_system.add_customer(customer1)
delivery_system.add_customer(customer2)

# Create some restaurants with menus
pizza_place = Restaurant("Pizza Place", {"Pizza": 10.99, "Burger": 7.99, "Pasta": 8.99})
sushi_spot = Restaurant("Sushi Spot", {"Sushi Roll": 12.99, "Tempura": 9.99, "Miso Soup": 3.99})

# Add restaurants to the system
delivery_system.add_restaurant(pizza_place)
delivery_system.add_restaurant(sushi_spot)

# Create a delivery person
delivery_person1 = DeliveryPerson("John")

# Add delivery person to the system
delivery_system.add_delivery_person(delivery_person1)

# Display available restaurants
print("Available Restaurants:")
delivery_system.show_restaurants()

# Customer places an order
print("\nCustomer 1 places an order:")
delivery_system.place_order(customer1, pizza_place, "Pizza")

# Another customer places an order
print("\nCustomer 2 places an order:")
delivery_system.place_order(customer2, sushi_spot, "Sushi Roll")
22 changes: 22 additions & 0 deletions B4/Solutions/object_oriented_design/hotel_booking/features.text
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Explanation

1. Room Class:

a. Represents a hotel room with attributes for room number, type, price, and availability.
b. Methods include book_room (to book the room) and release_room (to make the room available again).

2. Customer Class:

a. Represents a customer who can book rooms.
b. Includes a method make_booking that attempts to book a room and create a Booking object if successful.

3. Booking Class:

a. Represents a booking made by a customer.
b. Calculates total price based on the duration of the stay and the room price.
c. Includes a method cancel_booking to release the room and remove the booking from the customer’s list.

4. Hotel Class:

a. Manages the collection of rooms.
b. Provides methods to add rooms, search for available rooms, and display all rooms.
Loading