Oops&Ds Notes
Oops&Ds Notes
examples.
Topic: Classes and Objects
Definition
Class: A blueprint for creating objects. It defines a set of attributes and
methods that the created objects will have.
Example in OOP
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print(f"Product: {self.name}, Price: {self.price}")
Class: Product
In Amazon, each product listed on the site can be represented as an object of the
Product class. The Product class contains attributes such as the product name,
price, description, stock quantity, and category. Methods might include actions
like adding the product to the shopping cart or displaying detailed information
about the product.
Where it is used: When you browse Amazon and see a list of products, each
product is an object instantiated from a product class. The system uses these
objects to display information, manage inventory, and handle user actions such as
adding products to the cart or wish list.
Topic: Inheritance
Definition
Inheritance: A mechanism where a new class (child class) inherits attributes
and methods from an existing class (parent class). This allows for code
reusability and the creation of a hierarchical relationship between classes.
Example
class Electronics(Product):
def __init__(self, name, price, brand):
super().__init__(name, price)
self.brand = brand
def display_info(self):
print(f"Product: {self.name}, Price: {self.price}, Br
and: {self.brand}")
Topic: Encapsulation
Definition
Encapsulation: Encapsulation is the concept of bundling the data (attributes)
and the methods (functions) that operate on the data into a single unit, called a
class. It restricts direct access to some of the object's components, which is a
means of preventing unintended interference and misuse. Encapsulation is
often achieved through the use of private and public access specifiers.
Example
class Product:
def __init__(self, name, price):
self.__name = name # private attribute
self.__price = price # private attribute
Class: Customer
Where it is used: When you log in to Amazon and update your profile information,
the system uses encapsulated methods to safely and securely handle your data.
For instance, setting a new password involves validation checks to ensure it meets
security standards before it is updated.
Encapsulation is crucial for maintaining the integrity of data and ensuring that the
internal state of an object is not directly accessible from outside the class. This
concept is widely used in applications like Amazon to manage user data, product
details, and other sensitive information securely.
Topic: Polymorphism
Definition
Polymorphism: Polymorphism is the ability of a function, method, or object to
take on multiple forms. In object-oriented programming, it typically refers to
the ability to use a single interface or method to represent different underlying
forms (data types). This can be achieved through method overloading (same
method name, different parameters) and method overriding (same method
name in different classes with a parent-child relationship).
Example in OOP
Method Overloading (Not directly supported in Python but can be simulated):
class MathOperations:
def add(self, a, b, c=0):
return a + b + c
Method Overriding:
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Dog(Animal):
def make_sound(self):
print("Dog barks")
class Cat(Animal):
def make_sound(self):
print("Cat meows")
# Creating objects
animals = [Animal(), Dog(), Cat()]
Amazon allows customers to pay using various methods, such as credit cards,
PayPal, and gift cards. Each payment method has different implementation details
but shares a common interface for processing payments. Polymorphism allows
Where it is used: When you select a payment method at checkout, Amazon uses
polymorphism to handle the payment processing. Regardless of whether you
choose a credit card, PayPal, or a gift card, the system calls the process_payment()
method on the chosen payment object, which internally handles the specifics of
that payment method.
Polymorphism allows for flexibility and the ability to extend the system with new
payment methods without modifying existing code that uses the PaymentMethod
interface.
Topic: Abstraction
Definition
Abstraction: Abstraction is the concept of hiding the complex implementation
details and showing only the essential features of the object. It is used to
reduce programming complexity and effort by providing a simplified interface
to interact with complex systems. Abstraction allows focusing on what an
object does instead of how it does it.
Example
class PaymentMethod(ABC):
@abstractmethod
def process_payment(self, amount):
pass
class CreditCard(PaymentMethod):
def process_payment(self, amount):
print(f"Processing credit card payment of ${amount}")
class GiftCard(PaymentMethod):
def process_payment(self, amount):
print(f"Processing gift card payment of ${amount}")
In Amazon, the order processing system handles different types of orders such as
physical products, digital products, and subscriptions. Each type of order has
specific processing logic. Using abstraction, Amazon can define a general
interface for order processing while allowing specific order types to implement
their unique processing details.
Where it is used: When you place an order on Amazon, the system uses
abstraction to process your order. Regardless of whether you are ordering a
physical book, a digital ebook, or subscribing to a service, the order processing
Data Structures
Topic: Stack
Definition
Stack: A stack is a linear data structure that follows the Last In, First Out
(LIFO) principle. This means that the last element added to the stack is the first
one to be removed. It is analogous to a stack of plates, where you can only
add or remove the top plate. Stacks are used in various applications, including
function call management, expression evaluation, and backtracking
algorithms.
Basic Operations
Push: Add an element to the top of the stack.
Pop: Remove and return the top element from the stack.
Example
class Stack:
def __init__(self):
self.items = []
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Pop from empty stack")
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
raise IndexError("Peek from empty stack")
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.peek()) # Output: 2
print(stack.is_empty()) # Output: False
In Amazon, a stack can be used to manage the browsing history. Each time a user
views a product, it is pushed onto the stack. When the user hits the back button,
the most recently viewed product is popped from the stack and displayed.
Where it is used: When you click on different product links and use the back
button in your browser, Amazon's system uses a stack to keep track of the
browsing history, allowing you to go back to the last viewed product.
In this example, the BrowsingHistory class uses a stack to manage the user's
browsing history. Each product visit is pushed onto the stack, and the back
navigation pops the most recent product from the stack.
Topic: Queue
Definition
Queue: A queue is a linear data structure that follows the First In, First Out
(FIFO) principle. This means that the first element added to the queue will be
the first one to be removed. Queues are commonly used in scenarios where
order of processing is important, such as task scheduling, handling requests in
web servers, and managing print jobs.
Basic Operations
Enqueue: Add an element to the end of the queue.
Dequeue: Remove and return the front element from the queue.
Example
class Queue:
def __init__(self):
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
else:
raise IndexError("Dequeue from empty queue")
def front(self):
if not self.is_empty():
return self.items[0]
else:
raise IndexError("Front from empty queue")
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Example usage
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue()) # Output: 1
print(queue.front()) # Output: 2
print(queue.is_empty()) # Output: False
In Amazon, a queue can be used to manage customer orders. Each new order is
enqueued to the end of the queue. The order processing system dequeues the
orders from the front of the queue to process them in the order they were
received.
Where it is used: When you place an order on Amazon, your order enters a queue
for processing. This ensures that orders are handled in the order they are placed,
maintaining a fair and organized system for order fulfillment.
In this example, the OrderQueue class uses a queue to manage customer orders.
Each new order is added to the queue using the place_order() method, and orders
are processed in the order they were placed using the process_order() method.
Definition
Linked List: A linked list is a linear data structure where elements (called
nodes) are linked using pointers. Each node contains two parts: data and a
reference (or pointer) to the next node in the sequence. Unlike arrays, linked
lists do not have a fixed size and can grow or shrink dynamically.
Doubly Linked List: Each node points to both the next and the previous nodes.
Circular Linked List: The last node points back to the first node, forming a
circle.
Basic Operations
Insertion: Add a new node to the list.
Example
Singly Linked List:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def traverse(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example usage
linked_list = SinglyLinkedList()
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.traverse() # Output: 1 -> 2 -> 3 -> None
linked_list.delete(2)
linked_list.traverse() # Output: 1 -> 3 -> None
Scenario: Users on Amazon can add items to their wishlist. The items in the
wishlist are managed in a sequence, and users can add or remove items as
they wish.
In Amazon, a linked list can be used to manage a user's wishlist. Each item added
to the wishlist is a node in the linked list. This allows for dynamic addition and
removal of items without needing to shift other items as in an array.
Where it is used: When you add items to your wishlist on Amazon, each item can
be represented as a node in a linked list. This allows Amazon to efficiently manage
the wishlist with dynamic updates as you add or remove items.
In this example, the Wishlist class uses a singly linked list to manage the items in a
user's wishlist. The add_item() method adds a new item to the end of the list, the
Where it is used: When you browse through recommended products, Amazon can
use a doubly linked list to manage the recommendations, allowing seamless
navigation between them.
Example Implementation:
class ProductNode:
def __init__(self, product_id, details):
self.product_id = product_id
self.details = details
self.next = None
self.prev = None
class ProductRecommendations:
def __init__(self):
self.head = None
def view_recommendations_forward(self):
current = self.head
while current:
print(f"Product ID: {current.product_id}, Details: {
current = current.next
def view_recommendations_backward(self):
current = self.head
while current and current.next:
current = current.next
while current:
print(f"Product ID: {current.product_id}, Details: {
current = current.prev
# Example usage
recommendations = ProductRecommendations()
recommendations.add_product("P1001", "Laptop")
recommendations.add_product("P1002", "Smartphone")
recommendations.view_recommendations_forward() # Output: Produc
recommendations.view_recommendations_backward() # Output: Produc
class ImageNode:
def __init__(self, image_id, url):
self.image_id = image_id
self.url = url
self.next = None
class ImageCarousel:
def __init__(self):
self.head = None
# Example usage
carousel = ImageCarousel()
carousel.add_image("I1001", "image1.jpg")
carousel.add_image("I1002", "image2.jpg")
carousel.add_image("I1003", "image3.jpg")
carousel.view_images(cycles=2) # Output: Images in a loop for s
Topic: Trees
Definition
Tree: A tree is a hierarchical data structure consisting of nodes, with a single
node called the root from which all other nodes branch out. Each node
contains data and references to its child nodes. Trees are used in various
applications, including representing hierarchical data, managing sorted data,
and facilitating fast data retrieval.
Basic Terminology
Root: The topmost node in a tree.
Height: The length of the longest path from the root to a leaf.
Types of Trees
Binary Tree: A tree where each node has at most two children.
Balanced Tree: A tree where the height difference between the left and right
subtrees of any node is at most one.
Heap: A special tree-based data structure that satisfies the heap property
(min-heap or max-heap).
Binary Tree
Use Case: Organizational Hierarchy
Heap
Use Case: Priority Queue for Order Processing
Topic: Graphs
Definition
Graph: A graph is a non-linear data structure consisting of a set of vertices
(nodes) and a set of edges connecting these vertices. Graphs are used to
Basic Concepts
Vertex (Node): Represents an entity in the graph.
Weighted Graph: A graph where edges have weights or costs associated with
them.
Types of Graphs
Directed Graph (Digraph): A graph where edges have a direction.
Weighted Graph: A graph where edges have weights or costs associated with
them.
Directed Graph
Use Case: Delivery Route Optimization
Undirected Graph
Use Case: Product Recommendations
Weighted Graph
Use Case: Shortest Path Finding
Scenario: Amazon's logistics system needs to find the shortest route between
warehouses to optimize delivery times. A weighted graph can represent the
distances between locations, with edge weights indicating travel distances.
2. Instagram
4. Amazon
5. Netflix
2. Instagram
3. YouTube
4. Amazon
5. Netflix
2. Instagram
3. YouTube
4. Amazon
2. Instagram
3. YouTube
5. Netflix
Explanation: When typing a message, users can undo their last action
by popping the last character or word from a stack. This feature allows
users to quickly correct typing mistakes without deleting the entire
message.
2. Instagram
3. YouTube
4. Amazon
5. Netflix
2. Instagram
3. YouTube
4. Amazon
2. Instagram
3. YouTube
4. Amazon
5. Netflix
Explanation: Netflix can use a B-tree data structure to index its vast
library of content. B-trees provide efficient storage and retrieval of
content metadata, ensuring fast access to titles for browsing and
streaming.
2. Instagram
3. YouTube
4. Amazon
5. Netflix