Computer 11th Class
Computer 11th Class
SCIENCE
Contents
2 Python Programming 30
4 Computational Structures 87
Answers 223
www.OnlineMathAcademe.com
www.OnlineMathAcademe.com
UNIT Introduction to
1 Software Development
Student Learning Outcomes
By the end of this chapter, students will be able to:
• Dene software development and explain its importance.
• Understand and describe key software development terminology, including
Software Development Life Cycle (SDLC), debugging, testicang, and design
patterns.
• Explain the stages of the SDLC and the objectives and activities involved in each
stage.
• Differentiate between various software development methodologies such as the
Waterfall model and Agile methodology.
• Plan a software project by setting timelines, estimating costs, and managing risks.
• Recognize and apply quality assurance techniques to ensure software standards.
• Utilize Unied Modeling Language (UML) diagrams to represent software systems.
• Identify and apply common software design patterns in software design.
• Employ debugging techniques and testing strategies to ensure software reliability.
• Understand and utilize various software development tools, including Integrated
Development Environment (IDEs), compilers, and source code repositories.
www.OnlineMathAcademe.com
Introduction
Software development is a systematic process that transforms user needs into software
products. It involves a series of stages, from initial analysis through design, coding,
testing, and deployment. Each stage has its own importance and requires specific skills
and tools. Understanding the software development process is crucial for creating
reliable, maintainable, and scalable software solutions. This chapter introduces the
fundamental concepts of software development, including key terminology, the
Software Development Life Cycle (SDLC), software development methodologies,
project planning and management, quality assurance, and software design patterns.
1.1 Software Development
Software development is the process of creating computer programs designed to
perform specific tasks. This involves writing code, testing it, and addressing any issues
that arise. Software development is important because it helps solve problems and
makes our lives easier. For example, software allows us to communicate with friends
through social media, helps us manage our money with banking apps, and makes
learning fun with educational games.
1.2 Introduction to Software Development Life Cycle
(SDLC)
Software Development Life Cycle (SDLC) is a framework that defines the processes used
by organizations to build an application from its initial conception to its deployment and
maintenance. The primary purpose of SDLC is to deliver high-quality software that
meets or exceeds customer expectations, reaches completion within time and cost
estimates, and works efficiently.
1.2.1 Framework in Software Development
In software engineering, a framework is a standardized and reusable set of concepts,
practices, and tools that provides a structured foundation for developing software
applications. It offers predefined components and architectures that facilitate the
implementation of specific software functionalities, allowing developers to focus on
writing code specific to their application rather than reinventing common solutions.
Frameworks promote efficiency, consistency, and code reusability, thereby improving
the overall quality and maintainability of software systems.
Example: Imagine you want to create a website. Instead of writing all the code from
scratch, you can use a framework like Django (for websites). Django comes with ready-
made features like user login, database management, and page templates. This is similar
to using a pre-designed blueprint to build a house instead of designing everything
yourself.
1.2.2 Stages involved in SDLC
The SDLC is an organized method for developing software that ensures it meets quality
2
www.OnlineMathAcademe.com
standards and functions properly. It is used by software developers and engineers to
guide the design, development, and testing of software. The SDLC consists of several
steps as shown in Figure 1.1. Each step has distinct tasks and goals.
www.OnlineMathAcademe.com
Functional and Non-Functional Requirements
Requirements are generally categorized into two types, functional and nonfunctional
requirements.
Functional Requirements
Functional requirements describe the specific behaviors or functions of a system. These
requirements outline what the system should do and include tasks, services, and
functionalities that the system must perform. They define the interactions between the
system and its users or other systems.
Example:
Functional Requirements for a Library Management System.
· User Registration: The system should allow users (students, faculty) to
register and create an account.
· Book Borrowing: The system should enable users to search for books and
borrow them.
· Book Return: The system should allow users to return borrowed books.
· Inventory Management: Librarians should be able to add, update, and
remove books from the inventory.
· Notification: The system should send notifications to users about due dates
and overdue books.
Non-Functional Requirements
Non-functional requirements define the quality attributes, performance criteria, and
constraints of the system. These requirements specify how the system performs a
function rather than what the system should do. They include aspects like usability,
reliability, performance, and security.
Example:
Non-Functional Requirements for a Library Management System.
· Performance: The system should handle up to 1000 simultaneous users without
performance degradation.
· Usability: The user interface should be intuitive and easy to navigate, allowing
users to perform tasks with minimal effort.
· Reliability: The system should be available 99.9% of the time, ensuring high
availability and minimal downtime.
· Security: User data should be encrypted, and access should be controlled
through secure authentication mechanisms.
· Scalability: The system should be able to scale to accommodate an increasing
number of users and books in the inventory.
www.OnlineMathAcademe.com
Differentiating Functional and Non Functional Requirements:
Functional Requirements Non-Functional Requirements
Define specific behaviors or functions of Define the quality attributes and constraints -
Think of this phase like designing a new house. You need blueprints to show where the
rooms and furniture will go before you start building.
1.1.1.1 Development
In the development phase, the actual creation of the software begins. This is where
programmers write the code, which is a set of instructions that the computer follows to
perform specific tasks. Based on the design specifications, which outline what the
software should do and how it should look, programmers translate these specifications
into a programming language. 5
www.OnlineMathAcademe.com
Think of it like following a recipe: the design specifications are the recipe, and coding is
the process of mixing and baking the ingredients to make a cake. Each line of code is like
a step in the recipe, ensuring the software works conectly and meets the requirements
set out in the design. During this phase, programmers also test their code to find and fix
any errors or bugs. This testing helps ensure that the software performs as expected and
is free from mistakes. If any issues are found, programmers revise the code, correct the
problems, and test again until the software is ready for the next stage.
1.1.1.2 Testing
Once the software has been developed, it undergoes a crucial phase called testing.
Testing is the process of checking the software to identify any bugs, errors, or issues.
Think of it as a quality check to make sure everything works as expected. During testing,
the software is run under various conditions to see if it behaves correctly. This includes:
· Functionality Testing: Ensuring all features of the software work according
to the specifications.
· Performance Testing: Checking if the software performs well under different
conditions, such as high traffic or heavy data.
· Compatibility Testing: Making sure the software works well on various
devices and operating systems.
Testing helps in identifying any hidden issues that were not apparent during
development. By fixing these issues, developers ensure that the software runs smoothly
and meets the user's needs, providing a better and more reliable experience.
1.1.1.3 Deployment
Once the software has been thoroughly tested and any issues have been fixed, it moves
to the deployment phase. Deployment is the process of making the software available
for users to access and use. This often involves several steps:
· Installation: The software is installed on the user's system or server. This may
involve running an installation program that copies files and sets up
necessary configurations.
· Configuration: The software is adjusted to fit the specific needs of the user
or organization. This can include setting up user preferences, network
settings, and database connections.
· Testing in the Real World: After installation, the software is tested in its real-
world environment to ensure it works correctly with other systems and meets
user needs.
www.OnlineMathAcademe.com
1.1.1.1 Maintenance
The final phase involves ongoing maintenance and updates. This ensures the software
continues to function correctly and adapts to any changes in user needs or technology.
Maintenance is like taking care of a plant. You need to water it regularly and address any
problems to keep it healthy and growing.
www.OnlineMathAcademe.com
· Maintenance: Make updates and fix any issues that come up after the
software is in use.
Benefits and Limitations
· Benefits:
1. Simple and Easy to Understand: The Waterfall Model is easy to follow
because it has clear, distinct phases
2. Sequential Process: Each phase is completed one at a time, which makes it
easier to manage and track progress.
3. Suitable for Small Projects: Works well for projects with clear, fixed
requirements where changes are unlikely.
· Limitations:
1. Inflexibility: Once a phase is completed, going back to make changes is
difficult and costly.
2. Not Ideal for Complex Projects: For projects with evolving requirements or
complex designs, this model can be challenging to use effectively.
3.
4. Risk and Uncertainty: The model assumes that all requirements are known
from the start, which can be risky if new needs or issues arise later in the
process.
www.OnlineMathAcademe.com
help teams deliver parts of the software rapidly and gather feedback early as shown in
Figure 1.3. Agile methods include practices such as:
· Continuous Integration: Regularly merging code changes into a central
repository to detect and fix issues early.
· Test-Driven Development: Writing tests before writing the code to ensure the
software works as expected.
· Pair Programming: Two developers work together at one workstation, with one
writing code and the other reviewing it in real-time.
www.OnlineMathAcademe.com
1.1.1.1 Other Methodologies
I. Scrum
Scrum is an agile framework widely used for managing and completing complex
software projects. It promotes iterative progress, collaboration, and flexibility, making it
well-suited for dynamic environments where requirements can change frequently. The
framework is built around a set of roles, events, and artifacts designed to create a
structured yet adaptable approach to project management.
Key Components of Scrum:
· Roles: The primary roles in Scrum are the Product Owner, Scrum Master, and
Development Team. The Product Owner defines the product backlog and
ensures that the team is working on the highest-priority items. The Scrum
Master facilitates the process, removes obstacles, and ensures that the team
follows Scrum practices. The Development Team, consisting of cross-functional
members, is responsible for delivering the product increments.
· Events: Scrum employs a series of events to ensure regular progress and review.
These include Sprints (time-boxed iterations), Sprint Planning, Daily Standups,
Sprint Reviews, and Sprint Retrospectives.
· Artifacts: Key artifacts in Scrum are the Product Backlog (a prioritized list of
features and requirements), Sprint Backlog (a list of tasks to be completed in a
Sprint), and Increment (the working product that is the result of the current
Sprint).
Suitable for Scrum: Scrum is particularly suitable for software projects that require
frequent updates and have evolving requirements, such as:
· Mobile Applications: Mobile app development often involves continuous
feedback and rapid iterations to meet user needs and stay competitive. Scrum's
iterative nature allows for quick adjustments based on user feedback and market
changes.
· Web Development: For web applications that require regular feature updates
and improvements. Scrum facilitates a responsive development process that can
quickly adapt to new requirements and user feedback.
Not Suitable for Scrum: Scrum may not be ideal for projects with well-defined
requirements and little expected change, such as:
· Embedded Systems: Development of embedded systems, which often involves
hardware integration and stringent regulatory requirements, may benefit from a
more traditional, linear approach rather than the iterative nature of Scrum.
· Safety-Critical Software: Projects such as medical software or aerospace
systems, where thorough documentation and extensive validation are crucial,
might not align well with the flexible and iterative nature of Scrum.
10
www.OnlineMathAcademe.com
Figure 1.4 illustrates the Scrum process flow, highlighting the key components and their interactions
within a Scrum framework.
www.OnlineMathAcademe.com
Figure 1.5: Lean Software Development Model
Suitable for Lean: Lean Software Development is particularly suitable for projects that
require rapid delivery and frequent iterations, such as startup software, mobile
applications, and web-based services. For instance, a startup developing a new mobile
app would benefit from Lean principles by quickly iterating on user feedback and
delivering updates that add value.
Not Suitable for Lean: Lean Software Development might not be ideal for projects that
require extensive upfront planning and are highly complex or regulated, such as large-
scale enterprise systems, embedded systems, or safety-critical applications. For
example, developing software for an aviation control system would demand rigorous
documentation, extensive testing, and regulatory compliance, which may not align well
with the iterative nature of Lean.
1.1.1.1 DevOps
DevOps is a set of practices that combines software development (Dev) and IT
operations (Ops) to enhance collaboration, efficiency, and agility in delivering software
products and services as shown in Figure 1.6. The primary goal of DevOps is to shorten
the development lifecycle, improve software quality, and provide continuous delivery
with high reliability.
Why DevOps Should Be Practiced: DevOps should be practiced because it brings
numerous benefits to the software development and delivery process:
1. Improved Collaboration: DevOps fosters a culture of collaboration between
development and operations teams, breaking down silos and ensuring that both
teams work towards common goals.
2. Faster Time-to-Market: By automating processes and enabling continuous
12
www.OnlineMathAcademe.com
integration and continuous delivery (CI/CD), DevOps allows teams to deliver
software updates and new features more rapidly.
3. Enhanced Quality: Continuous testing and monitoring in DevOps help identify
and address issues early in the development cycle, resulting in higher quality
software.
4. Increased Efficiency: Automation of repetitive tasks reduces manual effort and
the risk of human error, leading to more efficient workflows.
13
www.OnlineMathAcademe.com
1.4.1 Comprehensive Project Planning
Comprehensive project planning involves thinking about all the details of your project
before you start. This includes understanding what needs to be done, who will do it, and
how it will be done.
Some of the largest software development companies in the world
are worth billions of dollars! For example, as of 2023, Microsoft, one of
the leading software giants, has a market capitalization exceeding $2
trillion. This immense value highlights the significant impact and
economic importance of software development in today's digital age.
www.OnlineMathAcademe.com
· Development Team: The project requires a team of 1 project manager, 2
frontend developers, 2 backend developers, 1 UI/UX designer, and 2 QA testers.
· Technology Stack: The app will be developed using React Native for cross-
platform compatibility, Node.js for the backend, and MongoDB for the
database.
· Project Duration: The estimated duration is 6 months.
· Operational Costs: Costs include cloud hosting, development tools, and
software licenses.
· Risk Management: Potential risks include scope changes and technology
integration issues, with a contingency fund of 10% of total cost.
· Quality Assurance: Includes comprehensive testing phases to ensure
functionality and performance.
Cost Breakdown:
· Project Manager:
PKR 5,000/hour x 20hours/week x 24 weeks = PKR 2,400,000
· Frontend Developers:
2developers x PKR 3,500/hour x 30hours/week x 24weeks = PKR 5,040,000
· Backend Developers:
2developers x PKR 4,000/hour x 30hours/week x 24weeks = PKR 5,760,000
· UI/UX Designer:
PKR 3,000/hour x 20hours/week x 24 weeks = PKR 1,440,000
· QA Testers:
testers x PKR 2,500/hour x 20hours/week x 24 weeks = PKR 2,400,000
· Operational Costs:
Cloud services and tools = PKR 1,000,000
· Contingency Fund:
10% of the total estimated cost = PKR 1,604,000
Total Estimated Cost: PKR 19,644,000
Explanation: The total estimated cost of PKR 19,644,000 includes all aspects of
development, from planning and design to implementation and testing. This example
illustrates how different factors contribute to the overall cost and the importance of
detailed planning in cost estimation.
You don't need to know programming to start a software development project! You can
post your idea on freelancing platforms where developers can bid on your project. With
the help of your family, you can also seek out investors to fund your idea. This way, you can
bring your vision to life with professional help and turn your innovative ideas into reality!
15
www.OnlineMathAcademe.com
1.1.1 Risk Assessment and Management
Risk assessment and management are crucial aspects of any software project. They
involve identifying potential risks that could impact the project's success, analysing the
likelihood and impact of these risks, and developing strategies to manage them.
Effective risk management helps ensure that projects stay on track, within budget, and
meet quality standards.
Steps in Risk Assessment and Management:
1. Identify Risks: List all potential risks that could affect the project. These could be
technical risks, such as technology changes; operational risks, like resource
shortages; or external risks, such as market fluctuations.
2. Analyze Risks: Evaluate the likelihood of each risk occurring and its potential
impact on the project. This helps in prioritizing which risks need more attention.
3. Develop Mitigation Strategies: For each significant risk, develop a plan to
reduce its likelihood or minimize its impact. This could involve adding buffers to
the schedule, securing backup resources, or conducting additional testing.
4. Monitor and Review: Continuously monitor the project for new risks and
review existing risks to adjust strategies as necessary.
Example: A project is using a new, untested technology. The risk is that the technology
may not work as expected, causing delays and additional costs.
Mitigation Strategy: Conduct a small-scale pilot project to test the technology before
fully integrating it into the main project. This can help identify potential issues early and
provide a chance to address them without impacting the larger project.
Discussion: Figure 1.8 illustrates the risk management process, showing the steps from
identifying risks to monitoring and reviewing them. By following these steps, project
managers can systematically address risks, ensuring a smoother project execution.
1.1.2 Quality Assurance
Quality assurance ensures that a project meets set standards and works correctly. It
involves methods such as testing, reviewing code, getting feedback from stakeholders,
and regularly checking the project's progress.
Example: In a software project, this involves ensuring that the code is both accurately
written and functions as expected.
1.2 Graphical Representation of Software Systems
Graphical representation of software systems involves using visual diagrams to depict
various aspects of a software system's structure and behavior. This approach helps in
simplifying complex systems, making it easier for developers and stakeholders to
understand, communicate, and manage the system. Diagrams, like Unified Modeling
Language (UML) diagrams, are widely used to illustrate various components, their
16
www.OnlineMathAcademe.com
relationships, and interactions within software.
1.2.1 Introduction to UML
Unified Modeling Language (UML) is a standardized way to visualize the design of a
software system. It helps developers understand how a system works and
communicates. UML is important because it makes complex systems easier to
understand and manage.
www.OnlineMathAcademe.com
3. Outline Interactions: Describe the interactions between the actors and the
system to achieve these goals. Each interaction that results in a significant
outcome is a potential use case.
4. Validate Use Cases: Review the identified use cases with stakeholders to ensure
they accurately capture the required functionalities and interactions.
Class Activity
Objective: Learn to identify actors and use cases from a given statement
describing a system.
Instructions:
1. Read the following statement carefully.
2. Identify the actors involved in the system.
3. Identify the use cases that describe the interactions between the
actors and the system.
4. Write down your findings and be prepared to discuss them with the
class.
18
www.OnlineMathAcademe.com
Class Activity
Statement: Imagine you are designing an online shopping platform. The
platform allows customers to browse products, add items to their cart, and
make purchases. Additionally, the platform includes features for
administrators to manage product listings, process orders, and handle
customer inquiries. There is also a feature for delivery personnel to update the
status of deliveries.
In the above class activity, you can compare your findings with the
following:
· Actors:
o Customer
o Administrator
o Delivery Personnel
· Use Cases:
o Browse Products
o Add Items to Cart
o Make Purchase
o Manage Product Listings
o Process Orders
o Handle Customer Inquiries
o Update Delivery Status
1.1.1.1 What is a Class Diagram?
A class diagram is like a map that shows how things are organized in a system, just like
how you organize your room. It helps us see what's in each box (like your toys, books, or
clothes) and how these boxes are related.
Example:
In the example of s organizing your room:
· Room: Represents the overall space encompassing all other elements,
analogous to the main structure in a class diagram.
· Box: Serves as a container within the room, akin to a class in a
diagram.
· Attributes: Each box contains specific items, such as a 'ToyBox'
holding toys or a 'BookBox' containing books.
· Methods: Boxes can perform actions like 'open' or 'close,' similar to
methods in a class diagram that define what the box can do.
· Specific Boxes: Examples of specialized boxes include a 'ToyBox' for
toys, a 'BookBox' for books, and a 'ClothesBox' for clothes, representing
distinct instances of the general 'Box' class.
So, a class diagram is simply a way to organize and show how different parts of a system
(like your room) work together, making it easier to understand everything at a glance as
show in Figure 1.10.
19
www.OnlineMathAcademe.com
Figure 1.10: Class Diagram for Organizing Your Room
1.1.1.1 Sequence Diagrams
Sequence Diagrams show how objects in a system interact with each other in a particular
sequence. They help in understanding the flow of messages between objects over time.
Interactions:
· open(): User opens each box.
· put toys/books/clothes inside: User puts the respective items into the
boxes.
· close(): User closes each box.
Figure 1.11: Sequence diagram of the user organizing items into labeled boxes
20
www.OnlineMathAcademe.com
1.1.1.1 Activity Diagrams
Activity Diagrams illustrate the flow of activities or steps in a process. They are useful for
modeling the logic of complex operations.
Example: In a restaurant management system, an activity diagram can represent the
process from 'Order Placement' to 'Food Preparation' and finally to 'Order Delivery'.
Above activity diagram shows how a process flows from start to finish. In the restaurant
management system example, the process begins with ‗Start' moves to ‗Order
Placement,' then to ‗Food Preparation,' and finally to ‗Order Delivery.' The ‗End' node
concludes the process. Arrows indicate the sequence of these steps, making it easy to
follow how an order progresses.
1.5.3 Using UML to Represent Software Systems
UML can be used in various stages of software development to improve understanding
and communication. Here are some practical applications:
• Planning: Use UML diagrams to map out the system's requirements and design
before writing any code.
• Development: Developers refer to UML diagrams to understand the structure and
relationships within the system.
• Communication: UML diagrams help team members, including non-technical
stakeholders, to understand how the system works.
21
www.OnlineMathAcademe.com
1.6 Introduction to Design Patterns
Design patterns are a fundamental concept in software development, providing proven
solutions to common problems that arise during software development. They serve as
blueprints or templates that can be adapted to solve various design challenges, making
the development process more efficient and consistent.
22
www.OnlineMathAcademe.com
1.6.2 Applications of Design Patterns in Software Design
Design patterns are widely used in software development to solve common problems
and create robust and maintainable code. They help in:
· Reducing code complexity by providing a clear structure.
· Enhancing code reusability by using proven solutions.
· Improving communication among developers by providing a common
vocabulary.
Design patterns help create systems that are flexible, maintainable, and easy to
understand.
www.OnlineMathAcademe.com
· Code Reviews: Having other developers review your code to spot potential
errors.
1.7.1 Testing
Testing is the process of evaluating the software to ensure it meets the requirements and
works as expected. The testing process typically follows a hierarchy that begins with
smaller components and gradually progresses to the entire system, including user
acceptance. The main types of testing in this hierarchy are given below.
1.7.2.1 Unit Testing
Unit Testing is the first level of testing, where individual components or modules of the
software are tested in isolation. Each "unit" is a small, testable part of the software, such
as a function or method. The primary goal of unit testing is to verify that each
component works correctly according to its design and performs as expected.
Class Activity
Try writing a unit test for a simple function in your favorite programming
language.
www.OnlineMathAcademe.com
Requirement gathering is similar to planning a big event, like a
wedding? Just as you need to know the preferences of the bride and
groom, developers need to know what the users want from the
software.
www.OnlineMathAcademe.com
that software functions correctly and efficiently.
1.8.2 Language Editors
Language editors, also known as code editors, are tools that help developers write and
edit code in different programming languages. The purpose of language editors is to
provide a user-friendly interface for writing code. Examples include:
· Notepad++: A simple yet powerful code editor.
· Sublime Text: Known for its speed and ease of use.
· VS Code: A popular editor with many extensions.
1.8.3 Translators
Translators are tools that convert code written in one programming language into
another language that the computer can understand. Translators convert high-level
programming languages (like Python) into machine language (binary code) that
computers can execute.
· Interpreters: Translate code line-by-line (e.g., Python interpreter).
· Compilers: Translate the entire code at once (e.g., GCC for C/C++).
1.8.4 Compilers
Compilers are a type of translator that converts entire programs from high-level
languages into machine code before execution. The purpose of compilers is to optimize
and convert code into efficient machine code. Examples include:
GCC: GNU Compiler Collection for C and C++. Javac: Compiler for Java programs.
1.8.5 Debuggers
Debuggers are tools that help developers find and fix errors (bugs) in their code. The
purpose of debuggers is to allow developers to test their code and identify where emors
occur. Examples include:
GDB: GNU Debugger for C/C++.
Visual Studio Debugger: Integrated with Visual Studio IDE.
1.8.6 Integrated Development Environments (IDEs)
IDEs are comprehensive software suites that provide all the tools needed for software
development in one place. IDE integrate various development tools like editors,
compilers, debuggers, and version control systems to streamline the development
process. An IDE offers a unified interface where developers can write, test, and debug
their code efficiently.
Common IDEs
· Eclipse: Widely used for Java development.
· Visual Studio: Popular for .NET and C++ development.
· PyCharm: Preferred for Python development.
26
www.OnlineMathAcademe.com
1.8.7 Online and Offline Computing Platforms
These platforms provide environments where developers can write, run, and test their
code.
· Online Platforms: Cloud-based platforms accessible via the internet (e.g.,
Repl.it, Gitpod).
· Offline Platforms: Local development environments on a computer (e.g.,
local installations of IDEs).
1.8.8 Source Code Repositories
Source code repositories are platforms where developers can store, manage, and track
changes to their code. Repositories help in version control, allowing multiple developers
to work on the same project without conflicts. Repositories keep track of code changes
and maintain a history of all modifications.
· GitHub: Popular platform for open-source projects.
· Bitbucket: Used for both private and public repositories.
Summary
In this chapter, you were introduced to the essential aspects of software development,
from the fundamental concepts and key terminology to the detailed stages of the
Software Development Life Cycle (SDLC). You explored different software development
methodologies, including the Waterfall model and Agile methodology, and learned
how to plan and manage a software project effectively. The chapter also covered quality
assurance techniques, the use of UML for graphical representation, and the importance
of design patterns in software design. Finally, you were introduced to debugging
techniques, testing strategies, and various software development tools that aid in the
efficient development of high-quality software products.
www.OnlineMathAcademe.com
3. In the context of SDLC, what is the role of a framework?
a) To write code from scratch
b) To provide a structured foundation with predefined components and
architectures
c) To manage hardware
d) To perform manual testing
4. Which software development model involves working in short cycles or sprints?
a) Waterfall Model
b) Agile Methodology
c) Lean Software Development
d) Scrum
5. Which role is responsible for removing obstacles and facilitating Scrum practices?
a) Product Owner
b) Scrum Master
c) Development Team
d) Project Manager
6. Which of the following is not a benefit of DevOps?
a) Improved collaboration
b) Enhanced quality
c) Increased project scope creep
d) Faster time-to-market
7. What is a crucial aspect of comprehensive project planning?
a) Understanding the project scope and tasks
b) Deciding the project's colour scheme
c) Hiring a large development team
d) Ignoring potential risks
8. Which factor does NOT influence the cost estimation of a software project?
a) Scope of the project
b) Technology stack
c) Number of meetings held
d) Operational costs
9. What is the purpose of a contingency fund in cost estimation?
a) To cover unexpected costs
b) To pay for marketing expenses
c) To hire additional developers
d) To purchase new hardware
10. Which of the following is a purpose of Use Case Diagrams?
a) To document the system's architecture.
28
www.OnlineMathAcademe.com
b) To identify and document the system's functional requirements.
c) To illustrate the database schema.
d) To define the system's user interface design.
Short Questions
1. Differentiate between functional and non-functional requirements.
2. Explain why the testing phase is important in the Software Development Life
Cycle (SDLC), and provide two reasons for its significance.
3. Illustrate the concept of continuous integration in Agile Methodology and
discuss its importance in software development.
4. Identify the key components of the Scrum framework and analyze how each
contributes to effective project management.
5. Evaluate the main steps involved in risk assessment and management, and
assess their importance in a software project.
6. Explain the purpose of a Use Case Diagram in software development.
7. Compare and contrast a Sequence Diagram with an Activity Diagram,
highlighting the key differences.
8. Describe the Factory Pattern and explain how it differs from directly creating
objects, with an example.
Long Questions
1. Design a flowchart for a user registration process in a software application.
Outline its key steps.
2. Imagine you are managing a project to develop a simple mobile application.
Describe how you would use the Agile Methodology to handle this project.
3. You are working on a project that requires extensive documentation and has
very specific regulatory requirements. Discuss why the Scrum methodology
might not be suitable for this project and suggest an alternative methodology.
4. Consider an online banking system. Create a Use Case Diagram to show the
interactions between customers, bank staff, and the system.
5. You are developing a food delivery application. Create a Sequence Diagram to
show the process of placing an order, from the customer selecting items to the
delivery of the order.
6. Discuss the importance of software development tools in the software
development process.
a) Explain the role of language editors, translators, and debuggers in creating and
maintaining software.
b) Provide examples of each tool and describe how they contribute to the
efficiency and accuracy of software development.
29
www.OnlineMathAcademe.com
UNIT
Python Programming
2
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Understand basic programming concepts and set up a Python development
environment.
· Write and interpret basic Python syntax and structure, including variables, data
types, and input/output operations.
· Use various operators and expressions in Python, including arithmetic,
comparison, and logical operators.
· Implement control structures such as decision-making statements and loops in
Python.
· Work with Python modules, functions, and built-in data structures like lists.
· Apply modular programming techniques and object-oriented programming
concepts in Python.
· Handle exceptions, perform file operations, and apply testing and debugging
techniques in Python.
30
www.OnlineMathAcademe.com
Introduction
Welcome to the world of Python programming! Python is a popular, versatile language
known for its simplicity and readability, making it ideal for both beginners and
professionals. In this chapter, we will start with the basics, including setting up your
development environment and learning fundamental programming concepts. As we
move forward, we'll cover advanced topics like modular programming, file handling,
debugging, and data structures. By the end of this chapter, you will have a
comprehensive understanding of Python, enabling you to write, test, and debug your
own programs and Command Line Interface(CLI) applications.
2.1 Introduction to Python Programming
Python is a widely-used high-level programming language celebrated for its simplicity
and readability. It is versatile and applicable to various fields, including web
development, data analysis, artificial intelligence, and more. Python's straightforward
syntax and clear structure make it an excellent choice for beginners, allowing them to
focus on learning programming concepts rather than dealing with complex syntax rules.
Whether you're creating a simple script or developing sophisticated software, Python's
user-friendly nature helps you get started quickly and efficiently.
www.OnlineMathAcademe.com
efficient. We can download and install Python from https: //www. python. org/. When
starting with Python programming, choosing a good Integrated Development
Environment (IDE) can help make coding easier.
When installing Python, make sure to check the box that says "Add Python to PATH." This
makes it easier to run Python from the command line. We can also use oniline services to
write and run Python program.
www.OnlineMathAcademe.com
print ( age ="As - Salaam-Alaikum , dear students ! ")
age = 71
print( "Quaid-i-Azam lived for", age, "years")
age =60
print ( "Allama Iqbal lived for", age, "years")
This example illustrates how the variable “age” is assigned different values to represent
the ages of Quaid-i-Azam Muhammad Ali Jinnah and Allama Iqbal, which are then
printed as part of the output.
2.2.1.2 Variable Naming Rules in Python
Variable names in Python must adhere to the following rules:
· The name must begin with a letter (a-z, A-Z) or an underscore ( _ ).
· Subsequent characters can include letters, digits (0-9), or underscores ( _ ).
· Variable names are case-sensitive, meaning age and Age are considered two
different variables.
· Python's reserved keywords, such as for, while, if, etc., cannot be used as
variable names.
Always use meaningful names for variables to make your code easier to understand. For
example, use age instead of a.
• It's a good practice to use lowercase letters and underscores to separate words in
variable names (e.g., student_name). This style is known as snake_case.
• Remember, strings in Python are always enclosed in quotes, either single (' ' ) or
double (" ").
www.OnlineMathAcademe.com
message on the screen and waits for the user to type something and press Enter.
The text entered by the user is then stored in a variable. For example:
name = input("Enter your name: ")
This line of code asks the user to enter their name and stores it in the variable name.
· Output: Use the print () function to display information on the screen. The print
() function takes one or more arguments and displays them. For example:
print (" As - Salaam - Alaikum , " + name + "!")
This line of code displays a greeting message that includes the user's name.
2.2.1.5 Handling Integer and Float Inputs
To handle numeric inputs, you typically use the int() or float() functions to convert input
strings to integers or floating-point numbers, respectively.
Integer Inputs
# Example : Handling integer input
user_age = int(input("Ent er your age: "))
print("Your age is:",user_age)
Float Inputs
# Example: Handling float input
user_height = float(input("Enter your height in meters: ") )
print("Your height is", user_height,"meter")
2.3 Operators and Expressions
Operators are symbols that perform operations on variables and values. An expression is
a combination of variables, operators, and values that produces a result. Let's explore
different types of operators in Python.
1.2.1 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, modulus, exponentiation, and floor
division as shown in the following code. The code shows how to use basic arithmetic
operations in Python.
# Define variables
a= 10 b= 3
# Perform all arithmetic operations on these numeric variables
and print results
print(a, "+", b, "=", a + b) # Output: 10+3=13
print(a, "*", b, " = " , a * b) # Output: 10 * 3 = 30
print(a, "/", b, " = ", a / b)
34
www.OnlineMathAcademe.com
# Output: 10 / 3 = 3.3333333333333335
print(a, "//", b, " = ", a // b)
# Output: 10 // 3=3
print(a, "%", b, " = ", a % b)
# Output: 10 % 3 = 1
print(a, "**", b, " = ", a ** b)
# Output: 10**3= 1000
35
www.OnlineMathAcademe.com
1.1.2 Assignment Operators
Assignment operators are used to assign values to variables. The most common
assignment operator is the equal sign (=), which assigns the value on the right to the
variable on the left. There are also compound assignment operators like +=, -=, *=, and
/=, which combine arithmetic operations with assignment.
Above code illustrates the use of assignment operators in Python. The code comments
show the output of each operation.
1.1.3 Logical Operators
Logical operators are used to combine multiple conditions or expressions in a program.
The most common logical operators are and. or, and not. They are used to perform
logical operations and return Boolean values based on the evaluation of the expressions
involved.
# Define variables
x = True
y = False
# Logical AND
logical_and = x and y
print(x , "and ", y ,"=", logical_and) # Output: True and False =False
# Logical OR
logical_or = x or y
print(x , "or " , y , " =", logical_or) # Output: True and False = True
36
www.OnlineMathAcademe.com
# Logical NOT
logical_not_x = not x
print("not", x, " = " , logical_not_x) # Output not True= False
logical_not_y = not y
print("not", y, "=" , logical_not_y)
# Output: not False= True
The above code demonstrates the use of logical operators in Python. It defines two
Boolean variables, x and y, and performs logical operations such as AND, OR, and NOT
on them. The code also includes comments with the output of each logical operation.
2.3.5 Expressions
An expression is a combination of variables, operators, and values that produces a result.
For example, 3 + 4 is an expression that results in 7. More complex expressions can use
parentheses O to control the order of operations. For example:
result = (3 + 4) * 2 # result is 14
Class Activity
Write a program to calculate Body Mass Index (BMI). Ask the user for their
weight and height, then compute and display their BMI and classification.
The Body Mass Index (BMI) is calculated using the formula given below.
weight
BMI =
height
where:
· weight is in kilograms (kg)
· height is in meters (m)
www.OnlineMathAcademe.com
· Addition '+' and Subtraction '-': These have lower precedence compared to
multiplication and division.
· 5 + 2 evaluates to 7, and 10-4 evaluates to 6.
· Example: Consider the expression 3 + 2*5. The multiplication is performed before
the addition, so: 3 + 2*5 = 3 + 10 = 13
Class Activity
Compute the following expressions and compare results with your class
fellows and class teacher.
1. 10 + 3*2 **2-5/5
2. (10 + 3) * (2 ** (2 - 1)) / 5
Translate the following in Python's syntax
1. 5 + 3 x4-7 22 +1
2. 10 x (2 + 3) - 42 8 : 2 +5
www.OnlineMathAcademe.com
2.4.1.2 if-else Statement
The if-else statement allows us to execute one block of code if a condition is true and
another block if the condition is false.
# Syntax of if-else statement if condition:
If condition:
# code to run if the condition is true else :
else:
# code to run if the condition is false
Example: temperature = 15
if temperature > 30:
print("It’s a hot day ")
else :
print("It’s not a hot day " )
www.OnlineMathAcademe.com
weather = "cloudy" # The output depends on the va lue stored in the variable”
weather”
if weather == "sunny":
print("Wear sunglasses")
elif weather == "rainy":
print("Take an umbrella")
else :
print("Enjoy your day!")
Explanation: In this example, the code checks multiple weather conditions. If the
weather is “sunny”, the program prints “Wear sunglasses”. If the weather is “rainy”, the
program prints "Take an umbrella”. If the weather is neither “sunny” nor “rainy”, the
program prints “Enjoy your day!”.
Class Activity
Write an if-elif-else statement to check if a number is positive, negative, or zero.
2.4.1.4 Nested and Chained Conditionals
Sometimes, we need to check multiple conditions inside another condition. This is called
nesting.
# Syntax of nested if statement
if condition1:
if condition2:
# code to run if both condition1 and condition2 are
true
else:
# code to run if conditionl is true but condition2 is
false
else:
# code to run if conditionl is false
Example: If the weather is rainy and the temperature is below 15 degrees, we wear a
raincoat. If it is only rainy, we take an umbrella. If the weather is not rainy, we just enjoy
the day.
weather = "rainy"
temperature = 10
if weather == "rainy":
if temperature < 15:
print("Wear a raincoat")
else :
print("Take an umbrella")
else :
print("Enjoy your day!") 40
www.OnlineMathAcademe.com
2.4.2 Looping Constructs
Loops help us repeat actions, making our code more efficient and easier to read. There
are two main types of loops in Python: while loops and for loops.
2.4.2.1 while Loop
A while loop runs as long as a condition is true. It checks the condition before each
iteration and stops running when the condition is no longer true.
# Syntax of while loop while condition:
# code to run while the condition is true
Example: Add 1 to a number until it reaches 10.
number = 1
while number < 10:
print(number)
number += 1
Explanation: In this example, the code starts with a number set to 1. The 'while' loop
checks if the number is less than 10. If it is, the program prints the current value of the
number and then adds 1 to it. This loop continues until the number reaches 10, at which
point the loop stops running.
Class Activity
Write a Python program that print even and count the odd numbers from 1 to
20 using a while loop.
Explanation: In this example, the code goes through each friend in the list and prints a
greeting message for each one.
Example 2: Calculate total price of items in a shopping cart
41
www.OnlineMathAcademe.com
cart = [
{"item": "Apple", "price": 0.5, "quantity": 4},
{"item": "Banana", "price": 0.2, "quantity": 10},
{"item": "Orange", "price": 0.75, "quantity": 3}
]
total_price = 0
for product in cart:
item_total = product["price"] * product["quantity"]
total_price += item_total
print(f"{product['item']} total: ${item_total:.2f}")
print (f "Total price of all items: ${total_price:.2 f}")
Output
Apple total: $2.00
Banana total: $2.00
Orange total: $2.25
Total price of all items: $6.25
Class Activity
Write a Python program that iterates over a list of temperatures and prints
“Warm” for temperatures above 20 degrees and “Cold” for temperatures 20
degrees or below.
Explanation: The above code generates numbers from 0 to 4 and prints each number.
42
www.OnlineMathAcademe.com
Class Activity
1. Write a for loop using range() to print the even numbers from 2 to 10.
2. Write a Python program that prints the first 10 multiples of 3 using a for
loop and the range() function.
43
www.OnlineMathAcademe.com
2.5.1.3 Default Parameters
Functions can have default parameter values, which are used if no argument is provided
during the function call.
Example: Define a function with a default parameter.
www.OnlineMathAcademe.com
2.5.2 Using Libraries and Modules
In Python, libraries and modules are like toolboxes full of useful tools that help you solve
different problems without having to build everything from scratch. In this section, we
explain how to import and use both standard and third-party libraries in your Python
programs. We will also explore how Python searches for these modules and how they
are organized in a package structure.
2.5.3 Importing and Using Libraries
Libraries are like pre-built toolkits that you can use without having to write all the code
yourself. Let's explore how to import and use different libraries with some simple
examples.
Example: Import the random library to generate random numbers.
import random
# Generate a random number between 1 and 10
number = random.randint(1, 10)
print("The random number is:", number)
Explanation: The random library helps you generate random numbers, which can be
useful in games, simulations, or even to pick a winner in a lucky draw.
Example: Import the datetime library to work with dates and times,
Import datetime
# Get the current date and time
current_time = datetime.datetime.now()
print("Current date and time:", current_time)
Explanation: The datetime library is very useful when you need to handle dates and
times in your program, such as logging events or setting reminders.
Example: Import the statistics library to perform statistical calculations.
import statistics
# Calculate the mean of a list of numbers
data = [23, 45, 67, 89, 12, 44, 56]
mean_value = statistics.mean(data)
print("The mean value is:", mean_value)
Explanation: The statistics library is a great tool for performing basic statistical
calculations, such as finding the mean, median, and mode of a set of data. This can be
particularly useful in data analysis tasks.
In short by using these libraries, you can save time and effort, allowing you to focus on
solving the specific problem at hand rather than reinventing the wheel.
45
www.OnlineMathAcademe.com
When importing libraries, make sure to only import what you need. You can explore the
more libraries at https: //docs .python, org/3/
Class Activity
Write a Python program that imports the random and statistics libraries. Use
random to generate a list of 10 random numbers between 1 and 50. Then, use
statistics to calculate and print the mean (average) of those numbers.
import random
number = random.randint(1, 10)
print(f"Random number: {number}") # ‘f’ is used to place the value of a variable in a
string
# Output:
# Random number: 7 (or any number between 1 and 10)
46
www.OnlineMathAcademe.com
Explanation: Here, random is part of Python's standard library, so it is found without any
issues.
Package Structure:
To manage large projects, you can organize modules into packages. A package is simply
a directory containing related modules. For example, if you're building an e-commerce
platform, you could create a package named ecommerce with modules like products
.py, customers .py, and orders.py.
Example: In ecommerce/products.py:
def 1ist_products () :
return ["Laptop","Mobile", "Tablet"]
In your main Script
from ecommerce import products
available_products = products.list_products()
print(available_products)
# Output :
# [’Laptop’, ’Mobile’, ’Tablet’]
Explanation: In this case, ecommerce is the package, and products.py is the module.
This structure helps you keep your code organized and manageable.
Organizing your modules into packages is like organizing books into sections of a
library—it makes finding and maintaining your code much easier.
www.OnlineMathAcademe.com
Explanation: This code creates a list named 'fruits1 containing three elements and then
prints the list.
2.6.1.2 Accessing List Items
You can access items in a list by referring to their index, starting from 0. Example: Access
and print the second item from the list of fruits.
fruits = ["Mango", ”Apple”, “” Banana”
print(fruits [1])
# Output: Apple
Explanation: The code initializes a list 'fruits' containing 'Mango', 'Apple', and 'Banana',
then prints the second item, 'Apple', using the index ' 1 '.
2.6.1.3 Modifying a List
You can modify list items by accessing them via their index and assigning a new value.
Example: Change the first item in the list to "Orange" and add a new fruit "Pineapple".
fruits = ["Mango", "Apple", "Banana"]
fruits [0] = "Orange"
fruits.append("Pineapple")
print(fruits)
# Output: [’Orange’, ’Apple’, ’Banana’, ’Pineapple’]
Explanation: The code modifies the first element of the 'fruits' list to 'Orange', appends
'Pineapple' at the end, and prints the updated list.
2.6.1.4 Methods and Operations on Lists
Python provides several built-in methods to work with lists. Here are a few useful ones:
• append (item) - Adds an item to the end of the list.
• remove (item) - Removes the first occurrence of an item from the list.
• sort () - Sorts the list in ascending order.
• reverse () - Reverses the order of the list.
Example: Add a new student to the list of students and then sort the list.
students = ["Ahmed", "Sara", "Ali"]
students.append("Hina")
students.sort ()
print(students)
# Output : [’Ahmed’, ’Ali’, ’Hina’, ’Sara’]
Explanation: The code creates a list of students, adds 'Hina' to it, sorts the list
alphabetically.
48
www.OnlineMathAcademe.com
2.6.1.5 List Operations
Lists also support various operations, such as slicing and concatenation.
Example: Slice a portion of the list and concatenate it with another list.
numbers = [1, 2, 3, 4, 5]
slice = numbers [1:4] # Gets items from index 1 to 3
extra_numbers = [6, 7]
combined = slice + extra_numbers
print(combined)
# Output : [2, 3, 4, 6, 7]
Explanation: The code slices the 'numbers' list from index 1 to 3, combines it with
'extra_numbers', and prints the resulting list '[2, 3, 4, 6. 7]'.
Example: Sort a list of student names and remove a specific name.
Use list methods like append() and remove () to efficiently manage and modify your lists.
For larger projects, organizing data in lists helps keep your code clean and manageable.
49
www.OnlineMathAcademe.com
2.6.2 Tuples
In Python, tuples are a type of data structure used to store an ordered collection of
items, similar to lists, but with a key difference: tuples are immutable, meaning their
values cannot be changed after creation.
Example
# Creating a tuple
my_tuple = (1, 2, 3, "Hello", 4.5)
# Tuple length
print(len(my_tuple)) # Output: 5
www.OnlineMathAcademe.com
Explanation: This code demonstrates list operations in Python: creating a list of fruits,
accessing elements using positive and negative indexing, and slicing the list with both
positive and negative indices.
Class Activity
Consider the following list, tuple, and string:
# List: [10, 20, 30, 40, 50, 60, 70, 80]
# Tuple: ("Math", "Science", "English", "History", "Geography")
# String: "Python Programming"
Perform the following operations:
1. Access and print the third element from each sequence (list,
tuple, and string).
2. Slice and print elements from index 2 to 5 from the list and the
tuple.
3. Slice and print characters from index 7 to the end of the string.
4. Use negative indexing to print the last two elements from the list
and the tuple.
5. Use negative slicing to print characters from the second last to
the last character of the string.
Write the Python code to perform these operations and print the results.
Indexing and slicing are powerful tools for working with sequences in Python. Practice
these techniques to become more proficient in manipulating data and accessing specific
parts of sequences.
www.OnlineMathAcademe.com
# main.py
def main ( ) :
print("This is the main function.")
if __name__ == "__main__" :
main()
Explanation: In this example, the main() function will only run if the script is executed
directly, not when it's imported elsewhere. This setup is useful in larger projects that
have multiple modules.
2.7.1 Working with Modules in Python
A module in Python is just a file that contains Python code, such as functions, variables,
and classes, which you can reuse in different parts of your program. Creating a module is
easy. Just write your Python code in a file and save it with a .py extension. Here's how to
create and use a module with the main, function:
Step 1: Create a module file named greetings .py.
# greetings.py
def say_As-Salaam-Alaikum () :
return "As - Salaam-Alaikum, everyone!"
Explanation: This creates a module called greetings with a function named say_As-
Salaam-Alaikum.
Step 2: Create another file named main. py to use this module. This file will contain the
main function, which is the starting point of your program:
# main.py
import greetings
def main () :
message = greetings.say_As- Salaam-Alaikum()
print(message)
if _ _name_ _ == "_ _main_ _": main ()
# Output : As - Salaam-Alaikum , everyone!
Explanation: In this example, when you run main.py. Python imports the greetings
module, calls the say_As-Salaam-Alaikum function, and prints the message. By
organizing your program this way, you can use the greetings module in other parts of
your application, and the main function clearly shows where your program begins.
52
www.OnlineMathAcademe.com
Using the main function with modules helps keep your code organized, making it easier
to maintain. Always use the main function to define the starting point of your program,
and use modules to separate different parts of your code.
Class Activity
Create a Python module named calculator .py that includes two functions:
1. add (a, b) - This function should return the sum of two numbers.
2. subtract (a, b) - This function should return the difference
between two numbers. Then, write a script named main. py that
imports your calculator module and uses these functions to perform
the following:
1. Print the result of adding 15 and 8.
2. Print the result of subtracting 10 from 25.
Make sure to run your main. py script and verify that the output is correct.
www.OnlineMathAcademe.com
2.8.1 Class and Objects
A class is like a template for creating things, and an object is an actual thing created from
that template. Imagine you want to make a toy car. You first need a blueprint or a
template that describes how the toy car should look and function. This template
includes details like:
• Color
• Size
• Number of wheels
• Type of material
The template is not an actual toy car; it's just a plan and it represents a class.
Using the template, you can create multiple toy cars. Each toy car made using the
template will have its own specific characteristics, like different colors or sizes. These are
the actual objects that you can play with. Each object is an instance of the class, meaning
it follows the plan to have its own specific characteristics.
2.8.1.1 Defining Classes and Creating Objects
In programming, we use classes as concepts to define what an object should be like.
www.OnlineMathAcademe.com
Using Methods: The describe method allows us to get a description of the toy car.
Self: self is a convention used in object-oriented programming (OOP) to represent the
instance of a class within its methods.
1.1.1.1 Access Modifiers
Access modifiers are keywords or mechanisms that define the accessibility of classes,
methods, and variables. In python there are following access modifiers:
• Public: Attributes and methods that are accessible from outside the class.
class Car:
def __init__(self , color): self.color = color # Public property
· Protected: Attributes and methods are accessible within the class and its subclasses
(derived classes).
class Car:
def __init__(self): self._protected_var = 20 # Protected variable
• Private: Attributes and methods that are not accessible from outside the class. Use
double underscores for private attributes.2.8.1.3class Car: def __init__(self , color):
self.__color = color # Private property
def get_color(self): return self.__color
color is private, meaning it cannot be accessed directly outside the class. The method
get_color () is used to access the private property.
Explanation: The first code snippet defines a 'Car' class with a public property 'color',
accessible directly. The second snippet defines a 'Car' class with a private property '_
_color', which can only be accessed via the 'get_ _color()' method.
2.8.1.3 Constructor and Destructor
• Constructor: Constructor is a special type of function which is used to initialize the
class variables. In Python the init () method is used to initialize an object's
properties when it is created.
class Car: def __init__(self , color): self . color = color
• Destructor: The____del () method is called when an object is deleted. It is used
for cleanup purposes.
class Car:
def _ _init_ _(self, color):
self . color = color
def __del__(self) :
print("Car with color", self.color , is being deleted . ")
The destructor here prints a message when the object is deleted, indicating cleanup.
Explanation: The 'Car' class initializes with a 'color' attribute and prints a message when
an instance is deleted, indicating the car with the given color is being removed.
55
www.OnlineMathAcademe.com
2.8.1.4 Association
Association represents a relationship between two classes. There are two types of
association:
• Aggregation: Represents a relationship where one class (e.g., Library) contains
another class (e.g., Book) but does not own it. Books can exist independently of the
library.
class Book :
def __init__(self , title):
self.title = title
class Library :
def __init__(self ) :
self, books = [ ]
def add_book(self, book):
self.books.append(book)
print("Book ", book.title, "added to the library.”)
Explanation: The above code made association by passing an instance of the 'Book'
class to the 'Library' class through the 'add_book' method, which appends the book to
the library's list of books.
Composition: Represents a relationship where one class (e.g., House) contains and
owns another class (e.g.. Room). Rooms cannot exist without a house.
class Room:
def __init__(self, name):
self.name = name
class House :
def __init__(self) :
self.rooms = [Room("Living Room"), Room( " Bedroom")]
print (“House with rooms created”)
www.OnlineMathAcademe.com
class Animal:
def make_sound(self): print("Animal sound")
class Dog(Animal):
def make_sound(self):
print("Bark!")
class Cat(Animal):
def make_sound(self):
print("Meow ! ")
Explanation: In the above code Dog and Cat inherit from Animal. Each subclass can
override the make_sound() method to produce specific sounds.
2.8.1.6 Polymorphism
Polymorphism refers to the ability of different objects to respond to the same method or
function call in their own unique way. It allows one interface to be used for a general
class of actions, with specific implementations based on the object.
This is useful for calling methods in a uniform way, even if different classes implement
them differently.
def animal_sound(animal):
animal.make_sound( )
dog = Dog( )
cat = Cat( )
anima1_sound(dog) # Output: Bark!
anima1_sound(cat) # Output: Meow!
Explanation: In the above code, animal_sound() can handle objects of different classes
(Dog and Cat) uniformly.
2.9 Advanced Python Concepts
Advanced Python concepts extend the foundational knowledge and empower
programmers to handle more complex tasks effectively. This section covers key topics
such as exception handling, which deals with managing errors gracefully, and file
handling, which involves reading from and writing to files. Mastering these concepts is
essential for developing robust and efficient Python applications.
2.9.1 Exception Handling
Exception handling is a mechanism to manage errors that occur during program
execution. It allows a program to continue running or gracefully terminate if an error
occurs, ensuring more robust and error-resilient code.
2.9.1.1 Try-Except Blocks
In Python, the try block lets you test a block of code for errors, and the except block lets
you handle errors if occur.
Example: 57
www.OnlineMathAcademe.com
Input a
try :
result =10/a # This line creates error if the value of ‘a’ is 0
except ZeroDivisionError:
print("You can’t divide by zero!")
Explanation: In this example:
• The try block contains code that might cause an error.
• The except block catches the ZeroDivisionError and handles it by printing a
message.
2.9.1.2 Finally and Else
The finally block always executes, regardless of whether an exception was raised. The
else block, if used, runs only if no exceptions were raised in the try block. These features
are useful for ensuring certain code always runs and for executing additional logic when
no errors occur.
try :
number "))
number = int(input("Ent er a result = 10 /
zero ! " )
number
except ZeroDivisionError:
print("You can’t divide by
except ValueError:
print (" Invalid input! Pleas The result e enter a valid number.")
else : is", resu Execution completed. It)
print (" f ")
inally :
print ("
www.OnlineMathAcademe.com
Explanation: In the above code:
• CustomError is a user-defined exception.
• The check_value () function raises CustomError if the value is negative.
2.9.1.4 File Handling
File handling involves reading from and writing to files. It is essential for storing data
persistently.
2.9.1.5 Opening, Reading, and Closing Files
To read a file, open it using the open() function, read its contents, and then close the file
to free up resources.
www.OnlineMathAcademe.com
• Append (a): Opens a file for appending. Data written to the file is added to the
end of the file.
• Read and Write (r+): Opens a file for both reading and writing. The file must exist.
2.10 Testing and Debugging in Python
In Python programming, testing and debugging are essential practices to ensure that
your code works correctly and efficiently.
2.10.1 Testing
Testing is the process of running your code with various inputs to check if it behaves as
expected. The goal is to find and fix any issues before the code is used in real-world
applications.
2.10.1.1 Types of Testing
• Unit Testing: Tests individual parts of the code (like functions or classes) in
isolation. Python's unittest module is commonly used for this.
• Integration Testing: Checks how different parts of the code work together.
• Functional Testing: Validates that the software behaves as expected from
the user's perspective.
• Regression Testing: Ensures that new changes don't break existing
functionality. Example: In this example, we use the unittest module to test the
add function. This ensures that the function returns the correct results by
checking various input values.
import unittest
def add (a , b) :
return a + b
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
if __name__ == ’__main__’:
unittest.main()
Explanation: This code defines a unit test for the 'add' function, which sums two
numbers. The 'TestMathOperations' class checks that 'add' correctly returns expected
results for given inputs.
2.10.1.2 Debugging
Debugging is the process of finding and fixing errors (bugs) in your code. It involves
identifying the root cause of problems and making the necessary changes.
2.10.1.3 Common Debugging Techniques
60
www.OnlineMathAcademe.com
• Print Statements: Adding print statements to check the values of variables at
different stages of the code.
• Debugging Tools: Using tools like pdb (Python Debugger) to step through the
code, inspect variables, and understand the flow of execution.
• Error Messages: Reading and interpreting error messages to locate the source of
the problem.
Example: In this example, the divide function is called with a zero denominator, causing
a ZeroDivisionError. The try-except block catches the error and prints an error message,
helping to identify and handle the issue.def divide(a, b) :
return a / b
try :
result = divide (10 , 0)
except ZeroDivisionError as e:
print("Error occurred:", e)
Explanation: This code defines a function 'divide' that divides two numbers. It then tries
to divide 10 by 0. which raises a 'ZeroDivisionError'. and catches this error to print a
descriptive message.
Summary
In this chapter, we learn the essentials of Python programming, starting from the setup
of your development environment to advanced programming techniques. We explored
basic syntax, operators, and control structures, providing you with the tools to write
effective Python code. You learned how to use functions, modules, and data structures
to manage and manipulate data efficiently. We also introduced key concepts of modular
programming and object-oriented programming. Lastly, we discussed exception
handling, file operations, and debugging methods to help you troubleshoot and refine
your code. With these skills, you are well-equipped to tackle more complex
programming tasks and build robust Python CLI applications.
61
www.OnlineMathAcademe.com
2. What should you do when installing Python to run it from the command line more
easily?
a) Uncheck "Add Python to PATH"
b) Choose a different IDE
c) Check "Add Python to PATH"
d) Install only the IDE
3. Which of the following is a valid variable name in Python?
(a) variablel
(b) Ivariable
(c) variable-name
(d) variable name
4. What is the output of the below code?
age = 25; pr int (" Age : " , age)
(a) Age: 25
(b) 25
(c) Age
(d) age
5. Which of the following operators is used for exponentiation in Python?
(a) *
(b) **
© (O //
(d) 7.
6. Which loop type in Python is used to iterate over a collection such as lists?
(a) while
(b) for
(c) do-while
(d) repeat
7. What does the range () function do in Python?
(a) Generates a list of numbers
(b) Creates a sequence of numbers
(c) Calculates the sum of numbers
(d) Prints a range of numbers
8. Which keyword is used to define a function in Python?
a) define
b) function
c) def
d) func
62
www.OnlineMathAcademe.com
9. What is the output of the below code?
temperature, humidity, wind_speed =25, 60, 15
print("Hot and humid" if temperature > 30 and humidity > 50 else
"Warm and breezy" if temperature == 25 and wind_speed > 10 else
"Cool and dry" if temperature < 20 and humidity < 30 else
"Moderate ")
(a) Hot
(b) Warm
(c) Cool
(d) Nothing
10. Which operation is used to combine two lists?
(a) combine()
(b) concatO
(c) +
(d) merge ()
Short Questions
1. Explain the purpose of using comments in Python code?
2. Describe the difference between integer and float data types in Python. Provide an
example of each.
3. Define operator precedence and give an example of an expression where operator
precedence affects the result.
4. How does the short hand if-else statement differ from the regular if-else statement?
5. Explain the use of the range() function in a for loop?
6. Explain how default parameters work in Python functions.
7. Explain why modular programming is useful in Python.
8. Explain the difference between a class and an object in Python.
Long Questions
1. Evaluate the following Python expressions.
(a) (18 / 3 +4 ** 2) - (2 * (7 - 3)) /(9 7, 4)
(b) (25 + 3 * 4 ** 2 - 6) / (2 ** 3 + 1)- 7
(c) (12 + 6 *(5-2)) ** 2 / ((4 ** 2 - 7) + 10)
(d) 45 / (2 ** 2 + 3 * 4) + 8 * (7 - 3)
(e) (14 *3 +5 ** 2 - 28) / (4 +2 ** 3) + 10 7. 3
2. Translating the following Mathematical Expressions to Python Syntax
3. (a)
15 x (3 + 22)
6-2x3
63
www.OnlineMathAcademe.com
(b)
7 + 22 1 7
(c)
12 + 5x4—(3+7) 2
2
2 x (5 - 24)
(d)
9x (23 + l)-15 + 3
(5 + 4) x (2 + 3) ~
4. Explain the concept of variables in Python.
5. Write a Python program that takes a number as input and checks whether
it is positive, negative, or zero using an if-elif-else statement.
6. Write a Python program using a while loop that prints all the odd numbers
between 1 and Also, count and print the total number of odd numbers.
7. Create a Python module named temperature_converter. py that includes
two functions:
(a) celsius_to_fahrenheit (c) - This function should convert a temperature from
Celsius to Fahrenheit using the formula F=|xC + 32.
(b) fahrenheit_to_celsius(f) - This function should convert a temperature from
Fahrenheit to Celsius using the formula C = | x (F — 32).
Then, write a script named main.py that imports your temperature_converter
module and uses these functions to perform the following:
(a) Convert 25 °C to Fahrenheit and print the result.
(b) Convert 77°F to Celsius and print the result.
64
www.OnlineMathAcademe.com
UNIT Algorithms and Problem
3 Solving
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Describe and classify computational problems.
· Explain the importance of algorithms in problem-solving.
· Apply the generate and test method to solve problems.
· Differentiate between solvable and unsolvable problems.
· Understand problem complexity and categorize problems (P, NP, NP-Hard, NP-
Complete).
· Identify common computational problems like sorting and searching.
· Use algorithm design techniques like divide and conquer, greedy methods, and
dynamic programming.
· Implement and compare algorithms such as Bubble Sort, Binary Search, BFS,
and DFS.
· Evaluate algorithms based on efficiency and scalability.
· Develop algorithmic thinking to solve problems systematically.
65
www.OnlineMathAcademe.com
Introduction
In this chapter, we will explore how to solve problems using algorithms, which are step-
by-step instructions for performing tasks. Understanding algorithms is essential not
only for computer science but also for everyday problem-solving. We will start by
learning what computational problems are and how to describe them clearly. Then, we
will look at different types of algorithms and how they can help us solve various kinds of
problems. We will also discuss how to measure the efficiency of algorithms to find the
best solutions. By the end of this chapter, you'll have the skills to think systematically and
create effective solutions using algorithms.
3.1 Understanding Computational Problems
A computational problem is a challenge that can be solved through a computational
process, which involves using an algorithm, i.e., a set of step-by-step instructions that a
computer can execute. The objective is to find a solution by following a finite sequence
of steps that a computer can perform.
• Input: The problem starts with an input, which is the data or information given to
the algorithm.
• Output: The solution or result produced by the algorithm after processing the
input.
• Process: The steps or rules (algorithm) that are applied to the input to generate
the output.
3.1.1 Characterizing Computational Problems
To solve a problem computationally, we need to understand its characteristics. This
involves identifying the inputs, the desired outputs, and the process needed to
transform the inputs into outputs.
3.1.1.1 Classifying Computational Problems
Computational problems can be classified into different categories based on their
characteristics and the methods required to solve them. Some common classifications
include:
· Decision Problems: Problems where the output is a simple “yes” or “no”.
· Search Problems: Problems where the task is to find a solution or an item that
meets certain criteria.
· Optimization Problems: Problems where the goal is to find the best solution
according to some criteria.
· Counting Problems: Problems where the objective is to count the number of
ways certain conditions can be met.
3.1.1.2 Well-defined vs. ill-defined Problems
Problems can also be categorized based on how clearly they are defined:
· Well-defined Problems: These problems have clear goals, inputs, processes, and
66
www.OnlineMathAcademe.com
outputs. For instance, the problem of determining if a number is even, is a well-
defined problem because it has a clear goal (determine if the number is even), clear
input (a single integer), a clear process (check if the number is divisible by 2), and a
clear output (even or odd) as shown in Figure 3.1.
· Ill-defined Problems: These problems lack clear definitions or may have
ambiguous goals and requirements. For instance, consider a project aimed at
“improving education in Pakistan”. This goal is vague and broad. The input might
include resources such as funding, teachers, and educational materials, but without
clear specifications on how much funding is needed, what kind of teachers are
required, or which educational materials are most effective.
Class Activity
Students will explore route optimization by drawing maps of their city that
include several colleges. Each student will create a map, marking at least five
colleges and assigning distances between them. The goal is to plan the
shortest possible route to visit each college exactly once and return to the
starting point.
67
www.OnlineMathAcademe.com
3.2 Algorithms for Problem Solving
Algorithms are step-by-step procedures for solving problems, much like a recipe
provides steps for cooking a dish. They form the backbone of computer science,
enabling machines to perform tasks efficiently. Understanding algorithms is essential
because they provide the logic behind software operations, allowing us to solve
complex problems, optimize performance, and ensure accuracy in various applications.
When learning about algorithms, try to relate them to real-life tasks you already know.
This will help you understand how algorithms work and why they are important.
www.OnlineMathAcademe.com
making the process more efficient.
3.2.1.3 Pros and Cones
· Pros:
1. Simplicity: The Generate and Test algorithm is easy to understand and
implement, making it a useful approach for simple problems.
2. Versatility: It can be applied to a wide range of problems, particularly when no
clear solution strategy exists.
3. Exhaustiveness: The algorithm explores all possible solutions, ensuring that
no potential solution is overlooked.
· Cones:
1. Inefficiency: The algorithm can be highly inefficient, especially for large
problem spaces, as it may require testing many possible solutions before
finding a valid one.
2. No Optimality Guarantee: The Generate and Test algorithm does not
necessarily find the optimal solution; it only guarantees a valid one. For
example, in optimization problems, it may find a solution that works but is not
the best possible.
3. Computational Expense: For problems with a vast number of potential
solutions, the algorithm may become computationally expensive and
impractical.
www.OnlineMathAcademe.com
3.3 Problem Solvability and Complexity
Understanding the solvability and complexity of problems is a fundamental concept in
computer science. It helps us determine whether a problem can be solved using an
algorithm and, if so, how efficiently it can be solved. This section explores the
distinctions between solvable and unsolvable problems, as well as tractable and
intractable problems, providing a foundation for understanding computational
complexity.
3.3.1 Solvable vs. Unsolvable Problems
In computer science, problems are classified as solvable or unsolvable based on whether
there exists an algorithm that can provide a solution.
Solvable Problems: A problem is considered solvable if an algorithm can solve it within
a finite amount of time. These problems have clearly defined inputs and outputs, and
there is a step-by-step procedure to reach the solution.
Example: Calculating the greatest common divisor (GCD) of two integers is a solvable
problem. The Euclidean algorithm provides a clear and finite method to determine the
GCD, making it a classic example of a solvable problem.
Unsolvable Problems: On the other hand, a problem is unsolvable if no algorithm can
be created that will provide a solution in all cases. These problems do not have a general
procedure that can guarantee a solution for every possible input.
Example: The Halting Problem is a famous example of an unsolvable problem. It
involves determining whether a given program will eventually halt (finish running) or
continue to run forever. Alan Turing proved that no general algorithm can solve the
Halting Problem for all possible program-input pairs, making it a fundamental example
of an unsolvable problem.
When tackling complex problems, it's essential to first determine whether the problem is
solvable. This saves time and resources by ensuring you are working on a problem that
can be resolved using an algorithm.
www.OnlineMathAcademe.com
tractable problem because these algorithms have a polynomial time complexity of O (n
log n), where n is the number of elements in the list.
Intractable Problems: Intractable problems are those that require super-polynomial
time to solve, often growing exponentially with the size of the input. These problems are
impractical to solve for large inputs because the time required becomes unmanageable.
Example: The Travelling Salesman Problem (TSP), where the goal is to find the shortest
possible route that visits a set of cities and returns to the origin, is an example of an
intractable problem. The problem is NP-hard, meaning that as the number of cities
increases, the number of possible routes grows factorially, making it infeasible to solve
exactly for large instances. Factorially means, multiplying all whole numbers from n
down to 1.
• For 2 cities: 2! = 2 x 1=2 possible routes.
• For 3 cities: 3! = 3 x 2 x 1=6 possible routes.
• For 4 cities: 4!=4 x 3 x 2 x 1 = 24 possible routes.
As you can see, the number of possible routes increases very rapidly as you add more
cities.
3.3.2 Complexity Classes (P, NP, NP-hard, NP-complete)
Understanding the complexity of problems involves classifying them into different
categories based on their solvability and the time required to solve them.
3.3.2.1 Class P
Class P refers to a category of problems that can be solved efficiently by a computer. In
simpler terms, these are problems where a computer can find a solution quickly, even as
the size of the problem grows:
problem grows.
Example: Let's consider a simple problem: sorting a list of numbers.
Suppose you have the following list:
[4, 1, 3, 2, 5]
The goal is to arrange these numbers in ascending order:
[1, 2, 3, 4, 5]
Class P and Sorting
· Easy to Solve: The sorting problem can be solved efficiently by a computer. As
the list gets larger, the time required to sort it increases at a manageable rate.
· Polynomial Time: This means the time needed grows in a predictable and
reasonable way. Example: Doubling the size of the list results in roughly double
the time needed.
· Deterministic Algorithm: Sorting uses a set of clear steps or a recipe. For
instance, the algorithm compares and swaps numbers to sort the list. Following
these steps always leads to the correct result if done correctly.
71
www.OnlineMathAcademe.com
How It Works
To sort the list [4, 1, 3, 2, 5], a computer might follow these steps:
1. Compare the first number with the second number. Swap them if needed.
2. Move to the next pair and repeat the process.
3. Continue until the entire list is sorted.
The time required to sort the list grows at a manageable rate as the list size increases. For
example, going from 5 numbers to 10 numbers will increase the time, but it remains
within a reasonable limit.
3.3.3.2 Class NP
Class NP refers to a category of problems for which, if a solution is given, it can be
checked quickly by a computer. These are problems where verifying a proposed solution
is easy, but finding that solution might be
difficult and time-consuming.
Example:
Consider a common example of solving a Sudoku puzzle. In Sudoku, you fill a 9 x 9 grid
with numbers so that each row, column, and 3 x 3 sub grid contains all digits from 1 to 9
exactly once as shown in Figure 3.5.
Class NP and Sudoku
· Verification is Easy: If someone gives you a completed Sudoku grid,
· you can quickly check if the solution is correct. You just need to ensure that each
row, column, and 3 x 3 sub grid contains all numbers from 1 to 9 without
repeating.
· Finding the Solution is Hard: Solving Sudoku from scratch, especially larger or
more complex puzzles, can be difficult and time-consuming. There is no simple,
fast way to guarantee a solution, which means finding the solution is not always
efficient.
· Non-deterministic Polynomial Time: Class NP problems can be solved quickly
if given a correct solution, but finding that solution might take an impractically
long time for large problems.
How It Works
In the context of Sudoku:
1. Checking a Solution: To verify if a Sudoku solution is correct, you can quickly
check each row, column, and subgrid to ensure they all have numbers 1 through 9
without repetition. This verification process is straightforward and efficient.
Solving the Puzzle: Finding the correct arrangement of numbers for a Sudoku puzzle
can be challenging. There are many possible configurations, and determining the
correct one involves lot of trial and error or advanced algorithm.
72
www.OnlineMathAcademe.com
Figure 3.3: A simple Sudoku Puzzle
3.3.3.3 Class NP-Hard
NP-hard problems are a class of problems that are at least as difficult as the hardest
problems in NP (Non-deterministic Polynomial time). Solving an NP-hard problem is
challenging, and no efficient algorithm is known for finding a solution. These problems
are usually very difficult and take a lot of time to solve, even when the cases are not very
large.
Example:
A well-known example of an NP-hard problem is the Traveling Salesman Problem (TSP),
we discussed in Section 3.3.2.
Why TSP is NP-Hard
· No Known Efficient Solution: There is no known algorithm that can solve
TSP quickly for large numbers of cities. As the number of cities increases, the
number of possible routes grows factorially, making the problem extremely
difficult to solve exactly.
· Computational Complexity: The time required to solve TSP grows so quickly
with the number of cities that it becomes impractical to compute the exact
solution for large instances. For example, with just 10 cities, there are
3,628,800 possible routes.
Illustration of Complexity
www.OnlineMathAcademe.com
3.3.3.4 NP- Complete
NP-Complete problems are a special subset of NP problems that are both in NP and as
hard as the hardest problems in NP. This means that these problems are particularly
challenging, and if you can solve one NP-Complete problem efficiently, you can solve all
problems in NP efficiently.
Example: A classic example of an NP-Complete problem is the Knapsack Problem.
The Knapsack Problem
In the Knapsack Problem, you have a knapsack with a maximum weight capacity and a
set of items, each with a weight and a value. The goal is to determine the most valuable
combination of items to put in the knapsack without exceeding its weight capacity.
Why the Knapsack Problem is NP-Complete
· Verification is Easy: If you are given a set of items and a proposed solution, you
can quickly check if the total weight is within the knapsack's capacity and if the
total value is correct.
· Solving the Problem is Hard: Finding the optimal combination of items to
maximize the total value while staying within the weight limit is challenging,
especially as the number of items increases.
· NP-Completeness: The Knapsack Problem is NP-Complete because it is both in
NP (you can verify a solution quickly) and as hard as the hardest problems in NP.
If you could solve the Knapsack Problem efficiently, you could solve all NP
problems efficiently.
Illustration of Complexity
To illustrate why the Knapsack Problem is NP-Complete:
· Small Instances: For a small number of items, it might be feasible to find the
optimal solution by checking all possible combinations.
· Larger Instances: As the number of items grows, the number of possible
combinations increases exponentially, making it impractical to solve the
problem by brute force
Figure 3.4 Venn diagram of the complexity classes P, NP, NP-hard, and NP-complete.
74
www.OnlineMathAcademe.com
Figure 3.4 shows a Venn diagram of the complexity classes P, NP, NP-hard, and NP-
complete. It visually represents the relationships between these classes, highlighting
how some problems can be solved efficiently, while others pose significant challenges
to computational theory.
The question of whether P equals NP is one of the most important
unsolved problems in computer science. It has significant
implications for cryptography, algorithm design, and the overall
understanding of computational complexity.Figure 3.4: Venn
Diagram of Complexity Classes P, NP, NP-hard, and NP-complete
www.OnlineMathAcademe.com
for might be the very last one on the list, meaning we would have to check all n
students. This process involves examining each student one by one, making the
search take a time proportional to n. Therefore, this example represents a linear
time complexity O(n), where the time taken increases directly with the number of
students.
• O(n2) Quadratic Time: The runtime grows quadratically as the size of the input
increases. For instance, consider a scenario where n students in a college are
participating in a programming competition, and we want to compare the
performance of each pair of students to determine the best team. To do this, we
must compare each student with every other student. The number of comparisons
required is the sum of the first n - 1 integers, which can be approximated as n(n -1).
Thus, the time complexity for this task is quadratic, represented as O(n2). The time
taken increases quadratically as the number of students n increases.
• O(log n) Logarithmic Time: The runtime grows logarithmically, meaning it
increases very slowly relative to the input size. For example, imagine a scenario
where you are playing a guessing game with n students in a college. One student
thinks of a number between 1 and n, and your task is to guess the number. After
each guess, the student will tell you whether the actual number is higher or lower
than your guess. By starting in the middle of the range and adjusting your guess
based on the feedback, you can quickly narrow down the possible numbers. The
number of guesses required to find the correct number is proportional to the
number of times you can halve the range, which is logarithmic in nature. Therefore,
the time complexity of this guessing process is O(log n).
www.OnlineMathAcademe.com
When comparing different time complexities, it's essential to understand how the time
required for an algorithm grows as the size of the input n increases. Constant time,
represented as O(1), remains unchanged regardless of the size of n. This means that no
matter how large the input is, the time taken will be the same, as seen by the flat line in
the graph.
3.4.1 Space Complexity
Space complexity measures how the amount of memory or space an algorithm uses
changes as the size of the input data increases. It helps us understand how efficiently an
algorithm uses memory when dealing with larger amounts of data.
Example: if an algorithm needs to store a list of numbers, its space complexity tells us
how much memory will be required as the volume of numbers increases.
Why Space Complexity Matters
Understanding space complexity is important because it helps us gauge the memory
requirements of an algorithm. Efficient use of memory is crucial, especially for large-
scale applications or systems with limited memory resources.
How Space Complexity is Analyzed
Space complexity is typically expressed using Big O notation, similar to time complexity.
It describes the upper limit on the amount of memory an algorithm will use as the input
size grows. Here are some common examples:
· O(1) Constant Space: The algorithm uses a fixed amount of memory regardless
of the input size. For example, a simple algorithm that only needs a few variables
to store intermediate values has constant space complexity.
· O (n) Linear Space: The memory usage grows linearly with the size of the input.
For instance, if an algorithm needs to store a list of items, the amount of memory
required increases directly with the number of items.
· O(n2) Quadratic Space: The memory usage grows quadratically as the size of the
input increases. For example, an algorithm that needs to store a matrix of size n x
n will have quadratic space complexity, as the number of elements in the matrix
increases with the square of n.
· O (log n) Logarithmic Space: The memory usage grows logarithmically,
meaning it increases very slowly relative to the input size. For instance, some algorithms
that use divide-and- conquer strategies may have logarithmic space complexity
because they only need to store a small portion of the data at each step.
77
www.OnlineMathAcademe.com
3.5 Algorithm Efficiency and Scalability
3.5.1 Efficiency
Algorithm efficiency refers to how well an algorithm uses resources like time and space
(memory) to solve a problem. The efficiency of an algorithm is typically evaluated based
on its time complexity (how the run time increases as the input size increases) and space
complexity (how the memory usage grows as the input size increases).
Example: Consider two sorting algorithms: Bubble Sort and Merge Sort. Bubble Sort
has a time complexity of O(n2), meaning that if the input size doubles, the time taken
increases by four times. Merge Sort, however, has a time complexity of O(nlog n), which
grows much more slowly as the input size increases, making it more efficient for large
datasets.
3.5.2 Scalability
Scalability refers to an algorithm's ability to maintain its efficiency as the size of the input
data grows. An algorithm that scales well will perform efficiently even when the input
data is significantly larger than what it was initially designed for.
3.5.3 Suitability for Specific Problems
Not all algorithms are suitable for all types of problems. The choice of algorithm
depends on the problem's specific requirements, such as the
need for speed, memory usage, or the nature of the data.
Example: Imagine you're looking for a book in a small, unorganized collection. The best
way is to check each book one by one, this is a Linear Search. Now, if your books are
neatly arranged alphabetically on a shelf, you can quickly find the book by starting in the
middle and deciding which half to search, this is a Binary Search.
3.6 Algorithm Design Techniques
Algorithm design is a critical aspect of problem-solving in computer science. It involves
creating systematic methods to solve problems efficiently and effectively. There are
several well-known algorithm design techniques that help in developing robust
algorithms for a variety of computational problems.
3.6.1 Divide and Conquer
Divide and Conquer is a powerful algorithm design
technique that works by breaking a large problem
into smaller, more manageable parts. Each smaller
part is solved independently, and then their solutions
are combined to solve the original problem, as
shown in Figure 3.6. This approach is particularly
effective for problems that can be divided into similar
smaller problems, making it easier to find a solution
step by step.
78
Figure 3.6: Merge Sort Process
www.OnlineMathAcademe.com
Example: Merge Sort is a classic example of a Divide and Conquer algorithm. The
algorithm begins by dividing an unsorted list into two halves. Each half is then sorted
independently, and finally, the two sorted halves are merged together to create the final
sorted list. Figure 3.6 illustrates the process of Merge Sort, showing how the list is
divided and then combined to produce a sorted output. This visualization highlights the
efficiency of the Divide and Conquer approach.
3.6.1 Greedy Algorithms
Greedy algorithms work by making a sequence of choices, each of which is locally
optimal, with the hope that these choices will lead to a globally optimal solution. The
greedy approach is often used when a problem has an optimal substructure, meaning
that the optimal solution to the problem can be constructed from optimal solutions to
its sub problems.
Example: A classic example of a greedy algorithm is the Coin Change problem. Suppose
you have coins of different denominations and you want to make a specific amount with
the fewest coins possible. The greedy algorithm would involve choosing the largest
denomination coin that does not exceed the remaining amount, then subtracting that
value and repeating the process until the desired amount is achieved.
Greedy algorithms are often faster and easier to implement than other techniques, but
they don't always guarantee the optimal solution for every problem. Always analyze the
problem to ensure that a greedy approach is appropriate.
www.OnlineMathAcademe.com
So the Fibonacci sequence begins like this: 0, 1, 1,2,3,5, 8, 13, 21, 34, and so forth. It is
named after Leonardo of Pisa, who is also known as Fibonacci, and it appears in many
interesting places in nature, such as the pattern of leaves on a stem, the branching of
trees, and even the arrangement of a pine cone's scales.
Class Activity
Implement a dynamic programming algorithm to solve the Fibonacci
sequence up to the 20th term.
3.6.1 Backtracking
Backtracking is a method used in solving problems where you build up a solution step by
step. If you find that a particular path doesn't lead to a solution, you simply go back and
try a different path. It's like trying out different routes on a map and turning back if you
find that you're going the wrong way. This method is often used for problems where you
need to look at all possible options, like with puzzles or problems that involve different
combinations.
3.7 Commonly Used Algorithms
Algorithms are essential tools in computer science and are applied to a wide range of
problems, from sorting data to searching for information in large datasets. Some
algorithms are foundational, serving as building blocks for more complex operations.
This section explores some of the most commonly used algorithms, including sorting,
searching, and graph traversal algorithms.
3.7.1 Sorting Algorithms
Sorting algorithms are used to arrange data in a particular order, such as ascending or
descending. Sorting is a fundamental operation that is often a prerequisite for other
tasks like searching and data analysis.
3.7.1.1 Bubble Sort
Bubble Sort is one of the simplest sorting algorithms. It works by repeatedly stepping
through the list, comparing adjacent elements, and swapping them if they are in the
wrong order. This process is repeated until the list is sorted.
Process:
• Start from the beginning of the list.
• Compare each pair of adjacent elements.
• Swap them if they are in the wrong order.
• Continue the process until no more swaps are needed.
Example: Consider the list [5,3,8,4,2]. Bubble Sort will compare 5 and 3, swap them, then
move to the next pair, and so on. After several passes through the list, the algorithm will
sort the list as [2,3,4,5,8].
Complexity: The time complexity of Bubble Sort is O(n2), making it inefficient for large
80
www.OnlineMathAcademe.com
datasets. However, it is easy to understand and implement, making it useful for
educational purposes and small datasets.
While Bubble Sort is easy to implement, consider using more efficient sorting algorithms
like Quick Sort or Merge Sort for larger datasets to save time and resources.
www.OnlineMathAcademe.com
In this case, you've found Islamabad in the list. If Islamabad weren't in the list, you would
check all the cities and then conclude that it's not there. This method is called a linear
search because you check each item in a straight line, from start to finish.
3.7.2.2 Binary Search
Binary Search is an efficient algorithm for finding an item in a sorted list. It works by
repeatedly dividing the search interval in half and discarding the half where the item
cannot be, until the item is found or the interval is empty.
Process:
• Start with the middle element of the sorted list.
• If the middle element is the target, return its position.
• If the target is smaller than the middle element, repeat the search on the left half.
• If the target is larger, repeat the search on the right half.
Example: Suppose you have a sorted list [1,3,5,7,9,11,13] and you are searching for the
number
• Binary Search will start at the middle element (7) and find the target immediately.
Complexity: The time complexity of Binary Search is O(log n), making it much faster
than linear search algorithms, especially for large datasets. Figure 3.7 illustrates the
binary search process, showing how the search interval is halved at each step, making
the search more efficient.
Binary Search is only effective on sorted lists. If your data isn't sorted,
consider using a sorting algorithm like Merge Sort before applying
Binary Search!
82
www.OnlineMathAcademe.com
3.7.3 Graph Algorithms
Graph algorithms are used to explore and analyze graphs, which are data structures
made up of nodes (vertices) connected by edges. These algorithms are essential for
network analysis, route planning, and social network analysis.
3.7.3.1 Breadth-First Search (BFS)
Breadth-First Search (BFS) is a graph traversal algorithm that explores all the nodes of a
graph level by level, starting from a given node (often called the root). It uses a queue to
keep track of the nodes that need to be explored.
Process:
• Start from the root node and enqueue it.
• Dequeue a node, process it, and enqueue all its unvisited neighbors.
• Repeat the process until the queue is empty.
Example: In a social network graph, where each node represents a person and edges
represent friendships, BFS can be used to find the shortest path between two people
(e.g., finding the degree of separation between two users).
Complexity: The time complexity of BFS is O(V + E), where V is the number of vertices
and E is the number of edges. This makes it efficient for exploring large graphs.
3.7.3.2 Depth-First Search (DFS)
Depth-First Search (DFS) is another graph traversal algorithm that explores as far down a
branch as possible before backtracking to explore other branches. It uses a stack to
manage the nodes to be explored.
Process:
• Start from the root node and push it onto the stack.
• Pop a node, process it, and push all its unvisited neighbors onto the stack.
• Repeat the process until the stack is empty.
www.OnlineMathAcademe.com
Example: DFS can be used in solving puzzles like mazes, where the algorithm explores
one possible path to the end, and if it hits a dead end, it backtracks and tries another
path.
Complexity: The time complexity of DFS is O (V+E), similar to BFS. However, DFS is more
memory-efficient for deep graphs, while BFS is more
suited for shallow graphs.
Figure 3.9 compares the BFS and DFS algorithms, showing how BFS explores a graph
level by level, while DFS explores as far as possible down each branch before
backtracking.
Class Activity
Implement both BFS and DFS algorithms to traverse a graph. Compare their
performance on different types of graphs (e.g., shallow vs. deep graphs) and
discuss in class which algorithm is better suited for specific scenarios.
Summary
This chapter offers a thorough introduction to algorithms and problem-solving. It
begins by defining and categorizing computational problems as solvable or unsolvable,
and tractable or intractable. Key algorithmic methods such as generate and test are
explained, alongside problem types like search, sorting, optimization, and decision
problems. It also explores design techniques including greedy algorithms, divide and
conquer, dynamic programming, and backtracking. The chapter further covers
commonly used algorithms, efficiency, and complexity analysis with Big O notation. It
highlights the importance of algorithmic thinking for effective problem-solving and
practical implementation, emphasizing the need to evaluate and balance trade-offs
based on specific problem requirements.
www.OnlineMathAcademe.com
3. Which of the following is true for unsolvable problems?
(a) They can be solved in polynomial time.
(b) They cannot be solved by any algorithm.
(c) They are always in NP class.
(d) They require exponential time to solve.
4. What does NP stand for in computational complexity?
(a) Non-deterministic Polynomial time
(b) Negative Polynomial time
(c) Non-trivial Polynomial time
(d) Numerical Polynomial time
5. Which of the following search algorithm is more efficient for large datasets?
(a) Bubble Sort
(b) Merge Sort
(c) Selection Sort
(d) Quick Sort
6. In which scenario Dynamic Programming is particularly useful?
(a) When problems do not have overlapping subproblems.
(b) When a problem can be solved by making a sequence of local choices.
(c) When problems have overlapping subproblems and optimal substructure.
(d) When a problem can be divided into independent subproblems.
7. Which of the following algorithms is used for sorting data by repeatedly stepping
through the list and swapping adjacent elements if they are in the wrong order?
(a) Selection Sort
(b) Quick Sort
(c) Bubble Sort
(d) Merge Sort
8. What is the time complexity of Depth-First Search (DFS) in a graph?
(a) O(n log n)
2
(b) O(V )
(c) O(V + E)
(d) O(n)
9. Which of the following best describes the time complexity?
(a) The amount of memory an algorithm needs to execute.
(b) The time taken by an algorithm to complete as a function of input size.
(c) The algorithm's ability to maintain efficiency as input size grows.
(d) The upper bound of an algorithm's space requirements.
85
www.OnlineMathAcademe.com
10. Which of the following algorithms has a time complexity of O(n log n)?
(a) Bubble Sort
(b) Binary Search
(c) Merge Sort
(d) Insertion Sort
Short Questions
1. Differentiate between well-defined and ill-defined problems within the realm of
computational problem-solving.
2. Outline the main steps involved in the Generate and Test algorithm.
3. Compare tractable and intractable problems in the context of computational
complexity.
4. Summarize the key idea behind Greedy Algorithms.
5. Discuss the advantages of using Dynamic Programming.
6. Compare the advantages of Breadth-First Search (BFS) with Depth-First Search (DFS)
in graph traversal.
7. Explain the importance of breaking down a problem into smaller components in
algorithmic thinking.
8. Identify the key factors used to evaluate the performance of an algorithm.
Long Questions
1. Discuss the different complexity classes (P, NP, NP-hard, NP-complete) and their
importance in understanding problem difficulty.
2. Provide a detailed explanation of why the Halting Problem is considered unsolvable
and its implications in computer science.
3. Discuss the characteristics of search problems and compare the efficiency of Linear
Search and Binary Search algorithm.
4. Discuss the nature of optimization problems and provide examples of their
applications in real-world scenarios.
5. Explain the Backtracking technique with reference to the N-Queens problem. Discuss
how the algorithm explores different configurations to solve the problem.
6. Explain the process and time complexity of the Bubble Sort algorithm. Compare it
with another sorting algorithm of your choice in terms of efficiency.
7. Discuss the differences between time complexity and space complexity. How do they
impact the choice of an algorithm for a specific problem?
86
www.OnlineMathAcademe.com
UNIT
Computational Structures
4
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Define and explain the purpose of primitive computational structures, including
lists, stacks, queues, trees, and graphs.
· Identify and describe the characteristics and properties of different
computational structures.
· Perform basic operations such as insertion, deletion, traversal, and searching on
various computational structures.
· Understand and implement the LIFO (Last-In, First-Out) and FIFO (First-In, First-
Out) principles in stacks and queues, respectively.
· Compare and contrast different types of trees and graphs, and apply appropriate
operations to them.
· Analyze and choose the most suitable computational structure based on
problem requirements, data organization, and performance considerations.
· Apply computational structures in real-world scenarios, including data
organization, task scheduling, and network modeling.
· Combine different computational structures to solve complex problems and
enhance functionality.
87
www.OnlineMathAcademe.com
Introduction
In this chapter, we will explore key computational structures, such as lists, stacks,
queues, trees, and graphs, which are fundamental in programming. We will examine
their properties, operations, and how to implement them efficiently. Additionally, we
will discuss selecting the appropriate structure based on specific problem requirements
and demonstrate their application in real-world scenarios. By the end of this chapter,
you will understand how to effectively use these structures in various contexts.
4.1 Primitive Computational Structures
In our daily lives, we often need to organize and manage data. For instance, think about
the way you store your contacts on your phone, keep a to-do list, or even stack plates in
your kitchen. Similarly, in the world of computers, we need to organize and manage
data. Computational structures help us do that.
4.1.1 Lists
A list is a data structure used to store multiple pieces of data in a specific sequence. Each
piece of data, known as an element, is positioned at a particular index within the list,
facilitating easy access and management.
4.1.1.1 List Creation
In Python, Lists are created using square brackets '[]', with each item separated by a
comma. Here's how you can create and work with a list in Python:
A type of list known as a linked list uses nodes, where each node
contains a value and a reference to the next node.
88
www.OnlineMathAcademe.com
4.1.1.2 List Properties
List has following properties:
1. Dynamic Size A list in Python can change its size. You can add new items to the list
or remove items without any problem. The list will automatically adjust to fit the
changes.
2. Index-Based Access Every item in a list has a position, called an index. The first item
has an index of 0, the second item has an index of 1, and so on. You can use these
indexes to get specific items from the list.
3. Ordered Collection The order in which you add items to a list is preserved. This
means that if you add an item first, it will stay in that position unless you change it.
4. Heterogeneous Elements A list can hold different types of items together. For
example, you can have numbers, words, and even other lists all in one list.
5. Mutability Lists are changeable, meaning you can update, add, or remove items
from the list after you create it.
6. Supports Duplicates A list can contain the same item more than once. This means
you can repeat values in the list if needed.
# Example List
items = ["Decorations", "Snacks", "Cold drinks", "Plates" "Balloons"]
# Characteristics of Lists:
# Nature of the Data Structure
print("List of items:", items)
# Mutability
items.append("Party Hats")
items.remove("Snacks")
print("After modifications:", items)
# Homogeneous vs. Heterogeneous
print("Homogeneous List:", [1, 2, 3, 4])
print("Heterogeneous List:", ["Apple", 42, 3. 14, True] )
# Properties of Lists:
# Length
print("Number of items:", len(items))
# Indexing print("Item at index 2:", items [2])
# Ordering print("Order maintained:", items)
# Duplication
print("List with duplicates:", ["Decorations", "Snacks", "cold drinks", "Snacks"])
89
www.OnlineMathAcademe.com
The code above shows different features of lists. First, it creates a list called 'items' with
party essentials, keeping the items in the order they were added. We then demonstrate
that lists can be changed by adding 'Party Hats' as a new item and removing 'Snacks',
which shows that lists are dynamic.
Did you know that lists in Python can be nested, meaning you can
have lists within lists? This feature is useful for representing complex
data structures.
# Output: [’’Invite friends’’, ‘’Buy cold drinks’’, ’’Buy decorations’’, ‘’Buy snacks’’,
“Order cake”]
c. Extending the List: You can also add multiple items at once using the 'extend()'
functions.
party_list = ["Invite friends", "Buy decorations ", "Buy snacks”, "Buy cold
drinks"]
party_list.extend(["Party hats", "Streamers"]) # Add multiple items at once
print(party_list)
# Output: [’’Invite friends’’, ’’Buy decorations’’, ‘’Buy snacks ‘’, ‘’Buy cold
drinks’’, ’’Party hats’’, ‘’Streamers’’]
90
www.OnlineMathAcademe.com
2. Deletion: Removing an item from your list is like crossing off a task you've
completed. You can remove items in various ways
a. Removing by Value: Use the 'remove()' function to delete the first occurrence of
a specific item.
party_list = ["Invite friends ","Buy decorations”, "Buy snacks”, "Buy cold drinks"]
party_list.remove ("Buy snacks”) # Removes ’Buy snacks ’ from the list
print(party_list)
# Output: [’Invite friends’, ’Buy decorations’, ’Buy cold drinks ’]
party_list = ["Invite friends ", "Buy decorations", "Buy cold drinks " ]
party_list.pop (0) # Removes the item at index 0
print(party_list)
# Output: [’Buy decorations’, ’Buy cold drinks’]
c. Removing All Items: Use the 'clear()' function to remove all items from the list.
3. Searching: Finding an item in a list is similar to looking for a specific task in your to-do
list. You can search for an item using different functions:
a. Checking for Existence: Use the 'in' keyword to check if an item exists in the
list.
91
www.OnlineMathAcademe.com
b. Finding the Index: Use the 'indexO' function to find the position of an item
in the list.
party_list = ["Invite friends", "Buy decorations", "Buy cold drinks " ]
index = party_list.index("Buy decorations") # Finds the position of ’Buy decorations’
print("Index of ’Buy decorations’:", index)
# Output: Index of ’Buy decorations’: 1
4.1.1.4 Applications of Lists
· Data Storage and Manipulation: Lists are commonly used to store and
manage collections of data, such as records, entries, or values. They allow for
easy insertion, deletion, and access to elements.
· Stack and Queue Implementations: Lists can be used to implement stack
(LIFO) and queue (FIFO) data structures, which are fundamental for various
algorithms and tasks in computing. Stacks and queues are discussed in
sections 4.1.2 and 4.1.4, respectively.
· Sorting and Searching Algorithms: Lists are frequently used in algorithms
for sorting and searching data. Algorithms like bubble sort, selection sort, and
binary search often operate on lists to arrange or find data efficiently.
· Function Arguments: Lists are often used to pass multiple arguments to
functions, enabling flexible and efficient handling of inputs in programming.
· Matrix Operations: Lists can be used to represent and manipulate matrices
in numerical and scientific computing, where each list represents a row or
column of the matrix.
4.1.2 Stacks
A stack is a simple data structure where you can only add or remove items from one end,
known as the “top”. Both insertion and deletion of elements occur at this top end. A stack
operates on the Last-In, First-Out (LIFO) principle, meaning that the most recently added
element is the first one to be removed.
4.1.2.1 Properties of Stack
· LIFO Principle: A stack works by the Last-In, First-Out rule. The last item
added is the first one removed.
· Single Access Point: You can only add or remove items from the top of the
stack.
· Order Preservation: The order in which you add items is preserved, with the
last item added being the first to leave.
· Size Flexibility: A stack can either have a fixed size or grow as needed.
Sequential Access: You can only access items in the order they were added, starting
from the top.
92
www.OnlineMathAcademe.com
Figure 4.2: Stack of Books
93
www.OnlineMathAcademe.com
The code creates an empty stack to hold books. It then adds three books (“Book A”,
“Book B”, and “Book C”) one by one to the top of the stack. Finally, it removes the top
book “Book C” from the stack, showing how the last book added is the first one taken off.
Did you know that stacks are used in algorithms like depth-first search
(DFS) in graph traversal? They help manage the nodes to be explored
in a LIFO manner.
www.OnlineMathAcademe.com
· If you find an operand, add it directly to the output list.
· If you find an operator (like +, -, *), push it onto the stack. But, if there is already
an operator on the stack with higher or equal priority, pop it from the stack to the
output list before pushing the new operator.
· If you find a left parenthesis (, push it onto the stack.
· If you find a right parenthesis), pop operators from the stack to the output list
until you find a left parenthesis. Remove the left parenthesis from the stack but
do not add it to the output list.
When you have processed the entire infix expression, pop any remaining operators from
the stack to the output list.
Example:
Convert the infix expression 3 + 4 * 2 to postfix notation.
· Start with an empty stack and output list.
· Read 3: Add to the output list: [3].
· Read +: Push to the stack: [+].
· Read 4: Add to the output list: [3, 4].
· Read *: Push to the stack (since * has higher priority than +): [+, *].
· Read 2: Add to the output list: [3, 4, 2].
· Pop all operators from the stack to the output list: [3, 4, 2, *, +].
Result: The postfix expression is 3 4 2 * +.
4.1.3.2 Evaluating Postfix Expression
To solve the above 3 4 2 *+, postfix expressions we can use a stack. Here's a step-by-step
guide: Example: Evaluate the postfix expression 3 4 5 *+ using a stack.
1. Start with an empty stack.
2. Read the expression from left to right.
3. When you find a number, push it onto the stack.
· Push 3 onto the stack: [3]
· Push 4 onto the stack: [3, 4]
· Push 5 onto the stack: [3, 4, 5]
1. When you find an operator, pop the required number of items from the
stack, perform the operation, and push the result back onto the stack.
· Pop 5 and 4, multiply them: 4 * 5 = 20
· Push the result 20 back onto the stack: [3, 20]
· Pop 20 and 3, add them: 3 + 20 = 23
· Push the result 23 back onto the stack: [23]
· The final result on the stack is the answer to the expression.
95
www.OnlineMathAcademe.com
4.1.3.3 Function Call Management:
Stacks are very useful in managing function calls in programming. Let's break it down
with a simple example: Imagine you are making a series of phone calls. Each time you call
someone, you write their name on a notepad. When you finish talking, you cross off their
name.
How This Works:
1. Making a Call: When you make a call, you write down the name on top of
the notepad. This is like pushing information onto the stack.
2. Ending a Call: After you finish talking, you cross off the name. This is like
popping information off the stack.
In programming, when a function is called, its details (like what it needs to do and where
to return after it's done) are written on the stack. This helps the computer remember
what to do next. When the function finishes, it removes (or pops) its details from the
stack, just like crossing off the name.
4.1.3.4 Balancing Parentheses:
When dealing with infix expressions, parentheses are used to show which operations
should be done first. Balancing parentheses is important to ensure that every opening
parenthesis has a matching closing parenthesis.
Steps to Check Parentheses:
1. Use a stack to keep track of opening parentheses.
2. When you find an opening parenthesis (, push it onto the stack.
3. When you find a closing parenthesis ), pop the top of the stack.
4. If the stack is empty after processing all parentheses, they are balanced.
5. If the stack is not empty, or if you try to pop from an empty stack, the
parentheses are not balanced.
Example: For the expression (3 + 4) * (5 - 2), the parentheses are balanced. Each (
has a matching ).
4.1.3.5 Undo Mechanism:
Stacks are used to implement undo functionality in applications such as Not Pad and
Microsoft Word. Each action you perform is saved on a stack. When you want to undo an
action, the most recent action is removed from the stack and reversed. This allows you to
go back to the previous state.
Example:
Imagine you are using a text editor and you make several changes to a document, like
typing new text or deleting old text. Here's how the undo mechanism works:
1. Performing Actions: As you make changes, each action (such as typing or
deleting text) is saved on a stack. For example, if you type “Hello”, this action is
96
www.OnlineMathAcademe.com
pushed onto the stack.
2. Undoing an Action: When you press the undo button, the most recent action
(like typing “Hello”) is removed from the stack. The text editor then reverses this
action (e.g., it deletes “Hello” from the document).
3. Multiple Undos: If you continue to press undo, each previous action is reversed
in the order they were performed. If you typed “World” after “Hello”, pressing
undo would first remove “World”, then “Hello”.
Class Activity
Consider the task of managing a stack of plates in a restaurant kitchen. Write a
python code to simulate the operations of adding and removing plates from
this stack.
Requirements:
1. Create a Stack Class:
· Define a Stack class using a list to represent the stack of plates.
· Implement methods for push (to add a plate), pop (to remove
a plate), and peek (to view the top plate without removing it).
2. Demonstrate Stack Operations:
· Push the following plates onto the stack: Plate 1, Plate 2, Plate
3.
· Display the stack after each addition.
· Pop a plate from the stack, and print both the removed plate
and stack.
· Peek at the top plate and print its value.
4.1.4 Queues
A queue is like a line in front of the a bank
or a ticket counter. The first person to get
in line is the first person to be served. In a
computer, a queue works the same way. It
keeps track of things so that the first item
added is the first one to be taken out. Just
like in a bank line, you add things to the
back and remove them from the front,
following the FIFO (First-In, First-Out)
principle, as shown in Figure 4.3.
97
www.OnlineMathAcademe.com
4.1.4.1 Properties of Queue
Below are the key properties of a queue.
· Order Preservation: A queue keeps track of the order of items. The first item
you put in the queue is the first one to come out.
· FIFO Principle: A queue works on the “First-In, First-Out” rule. This means the
first item added to the queue is the first one to be removed.
· Dynamic Size: A queue can grow or shrink in size as you add or remove
items. It adjusts automatically based on the number of items it holds.
4.1.4.2 Queue Operations
Queues support two primary operations:
· Enqueue (Add an Item): This is like adding a person to the end of the line. In a
queue, you add items to the back.
· Dequeue (Remove an Item): This is like serving the person at the front of the
line. In a queue, you take items out from the front.
· Additional operations might include checking if the queue is empty, retrieving
the element at the front without removing it, and determining the size of the
queue.
# Built-in module to implement queues in python
from queue import Queue
# Create a new queue
q = Queue ()
# Add people to the queue (Enqueue)
q. put (" Ahmed") # Adds Ahmed to the end of the queue
q.put ("Fatima") # Adds Fatima to the end of the queue
q.put ("Ali") # Adds Ali to the end of the queue
# View the person at the front of the queue (Peek)
front_person = q. queue [0] # Looks at the person at the front without
removing them
print(front_person) #Remove a person from the front of the queue
(Dequeue)
removed_person = q.getO # Removes and returns the person at the front
of the queue
print(removed_person)
# Add another person to the queue (Enqueue)
q.put("Sara") # Adds Sara to the end of the queue
# View the updated queue updated_queue = list(q.queue)
print(updated_queue)
98
www.OnlineMathAcademe.com
The code manages a line of people using a queue. It adds people to the end of the line,
checks who is at the front without removing them, and then serves (removes) the person
at the front. Finally, it adds another person to the end and shows the updated line.
The 'peek' operation allows you to view the element at the front of the queue without
removing it. It's similar to looking at the first book on the shelf to see which one will be
picked next.
www.OnlineMathAcademe.com
5. Continue Until the Queue is Empty: You keep following the queue until
there are no more enclosures left in it. When the queue is empty, it means
you have visited every enclosure in the zoo.
4.1.5.2 How We Traverse a Tree Using BFS ?
Breadth-First Search (BFS) is an algorithm used to explore and
traverse tree structures by visiting nodes level by level. This
approach uses a queue to manage the nodes that need to be
visited. Below is a detailed explanation using a numeric tree
example. The figure 4.4 illustrates the tree structure used in
our BFS example: Figure 4.4: Balanced Binary Tree
BFS Process with Queue Operations:
1. Start at the Root:
· Begin at the root node (1). This node is placed into the queue.
2. Queue: [1]
3. Visit Node 1:
· Dequeue node 1 and visit it.
· Add its children (nodes 2 and 3) to the queue.
4. Queue after visiting 1: [2, 3]
5. Visit Node 2:
· Dequeue node 2 and visit it.
· Add its children (nodes 4 and 5) to the queue.
6. Queue after visiting 2: [3, 4, 5]
7. Visit Node 3:
· Dequeue node 3 and visit it.
· Add its children (nodes 6 and 7) to the queue.
8. Queue after visiting 3: [4, 5, 6, 7]
9. Visit Node 4:
· Dequeue node 4 and visit it.
· Node 4 has no children, so the queue remains unchanged.
10. Queue after visiting 4: [5, 6, 7]
11. Visit Node 5:
· Dequeue node 5 and visit it.
· Node 5 has no children, so the queue remains unchanged.
12. Queue after visiting 5: [6, 7]
13. Visit Node 6:
· Dequeue node 6 and visit it.
· Node 6 has no children, so the queue remains unchanged.
100
www.OnlineMathAcademe.com
14. Queue after visiting 6: [7]
15. Visit Node 7:
· Dequeue node 7 and visit it.
· Node 7 has no children, so the queue is now empty.
16. Queue after visiting 7: []
17. Completion:
· The queue is empty, indicating that all nodes have been visited in a
level-by-level order.
4.1.5.3 Task Scheduling using a Queue
To understand task scheduling using a queue, let's compare it to a simple real-life
scenario at a doctor's clinic.
1. Tasks as Patients: Imagine that each task your computer needs to do is like a patient
visiting a doctor. Just as patients arrive at the clinic and wait their turn to see the
doctor, tasks arrive on your computer and wait to be processed.
2. Queue as the Waiting List: The queue in a computer works like a waiting list at the
clinic. It keeps track of all the tasks in the order they arrive, just like the list keeps track
of the patients. This ensures that tasks are handled one by one in the correct order.
3. Enqueue Operation: When a new task arrives (for example, when you press "Print"
on your computer), it is added to the end of the queue, similar to how a new patient
is added to the end of the waiting list. This process of adding a task to the queue is
called enqueue.
4. Dequeue Operation: As soon as the computer is ready to process a task, it removes
the first task from the front of the queue, just like the doctor calling in the next
patient from the waiting list. This process of removing a task from the queue for
processing is called dequeue.
5. Why Use a Queue? Using a queue ensures that tasks are processed in the order they
arrive, without skipping any. This is similar to ensuring that each patient is seen by
the doctor in the order they arrived. It helps the computer manage tasks efficiently
and fairly.
4.1.5.4 Print Spooling
Print spooling is a system used to manage print jobs sent to a printer, ensuring that they
are processed in the order they are received. This process involves the use of a queue to
maintain organization and efficiency.
· Managing Print Jobs: When multiple documents are sent to a printer, they are
placed in a queue, analogous to a line of people waiting at a service counter.
Each document is added to the end of the queue, which maintains the order of
arrival.
101
www.OnlineMathAcademe.com
· Order of Printing: The queue ensures that documents are printed sequentially,
based on the order they were submitted. The document that was sent first will be
printed first, while subsequent documents will wait their turn in the queue.
· Advantages of Using a Queue: By employing a queue, print spooling prevents
issues such as documents being printed out of sequence or confusion arising
from simultaneous print requests. This orderly approach allows the printer to
handle multiple tasks efficiently and fairly, maintaining an organized process.
4.1.5.5 Data Buffering
Queues play a crucial role in buffering data streams, which helps manage and process
data efficiently. To understand this concept better, let's look at a couple of real-world
examples.
1. Online Video Streaming: When you watch a video online, the video is not
played all at once. Instead, it is buffered in small chunks. This means that as
the video plays, a queue
stores and loads parts of the video ahead of what you are currently watching.
This buffering queue helps ensure that the video plays smoothly without
interruptions, even if there are delays in data transfer from the internet.
2. Printer Queue: Imagine you have several documents to print, but your
printer can only handle one document at a time. When you send multiple
print jobs to the printer, they are placed in a queue. The printer then
processes each document in the order they were received. This queue helps
manage and organize the print jobs so that each document is printed one
after the other without confusion.
4.1.6 Trees
A tree data structure organizes information in a way that spreads out from a main point
called the root node. In a tree, each piece of information, called a node, can connect to
other pieces, which are also nodes, forming a branching structure. This branching
structure is different from a list, where items are organized one after the other in a
straight line.
Example: In a family tree, the oldest ancestors represent the root node, serving as the
starting point of the hierarchy. Each individual in the tree may have descendants,
forming subsequent levels of the hierarchy, as illustrated in Figure 4.5. This hierarchical
structure is not suitable for storage in a linear format, such as a list, due to the complex
parent-child relationships. Therefore, a tree data structure is employed to efficiently
store and access such hierarchical data, enabling clear representation and retrieval of
information.
102
www.OnlineMathAcademe.com
Figure 4.5: Family Tree
Certainly! Here's a simplified version focusing on the core properties of trees, using
layman friendly language:
Here's a simple example of how to create a family tree structure in Python using classes.
This implementation shows how to create family members (nodes) and how to add
children (descendants) to them.
103
www.OnlineMathAcademe.com
class Fami1yMember :
def _ _init_ _ (self , name): self.name = name self.children = []
class FamilyTre e:
def _ _init_ _ (self , an c e s t o r _ n am e ) :
self.root = Fami1yMember(ancestor_name)
def add_child(self , parent_name , ctii 1 d_name ) :
parent_node = self._find_member(self.root, parent_name
if parent_node:
parent_node.children.append(FamilyMember( child_name))
def _find_member (self , current.member, name):
if current.member.name == name:
return current.member
for child in current_member.children:
result = self._find_member(child, name)
if result :
return result
return None
• Example usage
family_tree = FamilyTree (’Grandparent ’)
family_tree.add_child(’Grandparent’ , ’Parenti’)
family_tree.add_child(’Grandparent’, ’Parent2’) family_tree.add_child(’Parenti’,
’Childl’) family_tree.add_child(’Parenti’, ’Child2’)
www.OnlineMathAcademe.com
4.1.7 Balanced Tree
A Balanced Tree is a type of tree data structure where the height of the tree is kept as
small as possible by ensuring that the tree remains balanced. This balance is achieved by
maintaining that the height difference between the left and right subtrees of any node is
no more than a certain value
(commonly 1). Balanced trees are essential for efficient operations such as searching,
insertion, and deletion, as they keep these operations close to O(log n) time complexity.
Example: Organizing Books in a Library
Consider a library that needs to efficiently organize and locate books on shelves. If the
books were simply arranged in a linear order on a single shelf, finding a specific book
might require scanning through many books. Instead, imagine the books are organized
using a balanced tree structure.
At the root of this tree, we have a central category, such as Science. This category could
then be divided into subcategories like Physics and Biology, each forming the children
of the root. Within each subcategory, further divisions can be made, such as separating
Physics into Classical Mechanics and Quantum Physics, and Biology into Botany and
Zoology. This process continues, ensuring that no single branch of the tree becomes
significantly longer than the others.
105
www.OnlineMathAcademe.com
In this balanced tree, searching for a book on Quantum Physics involves traversing
down the branches of the tree: first to Science, then to Physics, and finally to Quantum
Physics. The balanced nature of the tree ensures that this search is quick, as the tree's
height remains logarithmic relative to the number of categories, avoiding lengthy
search times.
This concept is illustrated in Figure 4.7 while the computer science tree has upside down
as shown in Figure 4.8.
4.1.7.1 Operations on Tree
In a tree structure, there are some basic operations that help us manage and work with
the data. Let's break them down:
· Insertion: Imagine you're adding a new family member to your family tree.
Insertion is like finding the right spot in the tree and adding the new member
there. We connect the new person to their parent in the tree, making sure they
are part of the family structure.
Here's how you can insert a new member into the Family Tree:
· Deletion: Sometimes, we need to remove a member from the tree. Deletion is
the process of taking someone out of the family tree. We carefully remove them,
making sure the rest of the tree still makes sense and stays connected.
· Traversal: Tree traversal like walking through the family tree to visit each
member. There are different ways to do this, like starting from the top and
visiting each person one by one, or visiting all the children of a person before
moving to the next branch. There are three common types of tree traversals are
there: In-order, Pre-order, and Post-order. We will use the following simple tree
structure with numeric data to understand traversal functions more easily.
www.OnlineMathAcademe.com
This tree has a root node with the value 1. It has two child nodes, 2 and 3, which
themselves have children as shown in Figure 4.8.
1. In-order Traversal
In-order traversal means visiting the left subtree first, then the root node, and finally
the right subtree.
Example: The in-order traversal of the above tree is given below.
1. Visit node 4 (leftmost node of 2)
2. Visit node 2
3. Visit node 5 (right child of 2)
4. Visit node 1 (root)
5. Visit node 6 (leftmost node of 3)
6. Visit node 3
7. Visit node 7 (right child of 3)
The in-order traversal output is: 4, 2, 5, 1, 6, 3, 7.
2. Pre-order Traversal
Pre-order traversal involves visiting the root node first, then the left subtree,
followed by the right subtree.
Example: The pre-order traversal of the above tree is given below:
1. Visit node 1 (root)
2. Visit node 2
3. Visit node 4 (leftmost node of 2)
4. Visit node 5 (right child of 2)
5. Visit node 3
6. Visit node 6 (leftmost node of 3)
7. Visit node 7 (right child of 3)
The pre-order traversal output is: 1, 2, 4, 5, 3, 6, 7.
3. Post-order Traversal
Post-order traversal means visiting the left subtree first, then the right subtree, and
finally the root node. For our
Example: The post-order traversal of the above tree is given below:
1. Visit node 4 (leftmost node of 2)
2. Visit node 5 (right child of 2)
3. Visit node 2
4. Visit node 6 (leftmost node of 3)
5. Visit node 7 (right child of 3)
6. Visit node 3
7. Visit node 1 (root)
107
www.OnlineMathAcademe.com
The post-order traversal output is: 4, 5, 2, 6, 7, 3, 1.
Searching: Searching is like looking for a specific member in the family tree. We go
through the tree, checking each person until we find the one we're looking for.
This helps us quickly locate information in the tree.
4.1.7.2 Types of Trees:
Trees come in various types, each with its own unique structure and purpose. There are
two common types of trees: Binary Trees and AVL Trees. These types help in organizing
and managing data in efficient ways.
1. Binary Tree:
A binary tree is a hierarchical data structure in which each node can have at most two
children, known as the left and right children as shown in Figure 4.9. This structure is
analogous to a family tree, where each individual may have up to two descendants,
ensuring a well-organized and balanced arrangement of data for efficient management
and retrieval.
Example: In the binary tree example shown in figure 4.9:
1. The “Grandparent" is the root, and it has two children, “Parent1" and
“Parent2”.
2. Each parent can have their own children (like “Child1”, “Child2”. etc.).
108
www.OnlineMathAcademe.com
2. AVL Trees:
An AVL tree is a type of binary tree that keeps itself balanced, meaning the height of the
tree is managed carefully. If one side of the tree starts getting too tall compared to the
other, the tree rearranges itself to maintain balance.
Example: Imagine you are organizing books on shelves. You want to make sure that the
shelves are balanced, so one side isn't heavier than the other. This is similar to an AVL
tree as shown in Figure 4.10.
www.OnlineMathAcademe.com
4.1.8 Introduction to Graphs
A Graph is a data structure that consists of a set of vertices (or nodes) connected by
edges. Graphs are used to represent networks of connections, where each connection is
a relationship between two vertices. These vertices can represent anything, like cities,
people, or even abstract concepts, and the edges represent the relationships or
pathways between them.
Imagine you are mapping out all the cities in Pakistan and the roads that connect them.
Each city is a vertex, and each road between two cities is an edge. Unlike a tree, a graph
does not have a single ''root” and does not follow a hierarchical structure. In a graph, any
two vertices can be connected, creating a complex web of relationships.
Example: In a social network, each person can be connected to many others, forming a
graph. There is no single starting point, and people (vertices) can have multiple
connections (edges) that do not follow a strict parent-child relationship like in a tree.
Difference from a Tree: While both graphs and trees are used to represent
relationships between objects, a tree is a special kind of graph with some important
differences:
· A Tree is hierarchical, meaning it has a single root node from which all other
nodes branch out. In contrast, a Graph does not necessarily have a hierarchy
or a root.
· In a Tree, there is exactly one path between any two nodes, ensuring no
cycles (loops). However, in a Graph, there can be multiple paths between
nodes, and cycles are allowed.
· Trees are often used to represent structured data like family trees or
organizational charts. Graphs are more flexible and can represent a broader
range of connections, such as networks, web links, or transport systems.
4.1.8.1 Characteristics of Graphs
Graphs have several defining features that help us understand and use them effectively:
· Vertices (Nodes): These are the individual points or entities in a graph. For
example, in a social network graph, each user is represented by a vertex.
· Edges (Links): These are the connections between vertices. For example, in a
transport system graph, each road connecting two cities is an edge.
4.1.8.2 Properties of Graphs
Graphs also have specific details that describe their structure:
· Degree: This is the number of edges connected to a vertex. For instance, if a
city is connected to three other cities, the degree of that city's vertex is 3.
· Weight: In some graphs, edges have weights that represent values like
distances or costs. For example, if a road between two cities is 50 kilometres
long, its edge might have a weight of 50.
110
www.OnlineMathAcademe.com
· Direction: Edges can be either directed or undirected. Directed edges have a
one-way connection, meaning a road from city A to city B does not
necessarily have a return road from B to A. Undirected edges represent a two-
way connection.
4.1.8.3 Operations on Graphs
Graphs support various operations to manipulate and explore their structure. Here are
some essential operations:
· Insertion: Adding a new vertex or edge to the graph.
· Example: If a new city is added to the transport map, it introduces a new vertex
and possibly new edges.
· Deletion: Removing a vertex or edge from the graph.
· Example: If a city is removed from the map, its corresponding vertex and all
edges connected to it are deleted.
· Traversal: Visiting all vertices and edges systematically. Traversal can be done
using different functions:
· Breadth-First Search (BFS): This technique starts from a source vertex and
explores all its immediate neighbors before moving to the next level of vertices.
Example: Imagine you are at a central train station in a city, and you want to visit
all the nearby neighborhoods. First, you would take the trains that directly
connect to the central station and explore all the neighborhoods they reach.
Once you have visited all these neighboring areas, you then move to the next set
of neighborhoods that are directly connected to the previously visited ones. This
process continues until you have explored all reachable neighborhoods from
the central station.
· Depth-First Search (DFS): This technique starts from a source vertex
and explores as far as possible along each branch before backtracking.
· Example: Imagine you are exploring a multi-storey building. You start at
the entrance and decide to explore each floor completely before moving
to the next floor. You walk down each hallway and check every room on
the current floor before going up or down to the next floor. If you reach
the end of a hallway, you go back to explore any other rooms you might
have missed on that floor before moving to the next one.
· Searching: Finding a specific vertex or edge in the graph. Searching
operations help locate particular cities or routes efficiently.
4.1.8.4 Types of Graphs
Graphs can be classified into several types based on their structure and properties. The
main types of graphs are directed, undirected, and weighted. Each type has its own
characteristics, which can be better understood through simple examples.
111
www.OnlineMathAcademe.com
· Directed Graphs: In a directed graph, edges have a direction, which means
they go from one vertex to another in a specific way as shown in Figure 4.11.
112
www.OnlineMathAcademe.com
· Weighted Graphs: In a weighted graph, each edge has a weight or cost
associated with it. This weight represents the distance, time, or cost required
to travel from one vertex to another as shown in Figure 4.11.
Example: Imagine a map of a city where each road has a different distance or
travel time. If you want to travel from one landmark to another, the map
provides the distance or travel time for each road. This information helps you
determine the shortest or quickest route between landmarks.
Graph Implementation Using Python
Graphs can be implemented in Python using libraries such as NetworkX. Here's a basic
example:
import networkx as nx
import matplotlib.pyplot as pit
# Create a graph object
G = nx.Graph()
# Add vertices (nodes)
G . add_node( ’ A ’ )
G.add_node( ’B ’ )
G . add_node( ’ C ’)
# Add edges (links) between vertices
G. add_edge(’A’ , ’B ’)
G . add_edge(’B ’, ’ C ’)
# Draw the graph
nx.draw(G , with_labels=True)
pit.show ()
www.OnlineMathAcademe.com
easier to implement. Let's break down when each of the five data structures: Stack,
Queue, List, Tree, and Graph, is most appropriate.
4.2.1 Stack: Best for Last-In, First-Out (LIFO) Problems
When to Use: A stack is ideal when you need to process data in the reverse order of how
it was received. This is known as 'Last-In, First-Out' (LIFO). Stacks are often used in
scenarios where you need to backtrack, like in navigating through web pages (where
you can go back to the previous page) or evaluating mathematical expressions.
Common applications include:
· Expression Evaluation: Converting infix expressions to postfix or prefix, and
evaluating them.
· Backtracking Algorithms: Such as solving puzzles like mazes, or the Depth-
First Search (DFS) in graphs.
· Undo Mechanisms: In software like text editors, where you can undo the
most recent action.
4.2.2 Queue: Best for First-In, First-Out (FIFO) Problems
When to Use: A queue is perfect for scenarios where the order of processing needs to
follow the 'First-In, First-Out' (FIFO) principle. This means the first element added to the
queue will be the first one to be removed. Queues are commonly used in:
· Breadth-First Search (BFS): In graphs or trees, where you explore all nodes
at the current level before moving to the next.
· Task Scheduling: Where tasks are processed in the order they arrive, like
print job management or handling requests in a web server.
· Simulation of Real-World Scenarios: Such as modeling a line of customers
in a store.
4.2.3 List: Best for Ordered Collections
When to Use: Lists are versatile and useful when you need to store an ordered collection
of elements. They are especially appropriate when the order of elements matters, but
direct access to elements by index is also needed. Use lists in:
· Dynamic Arrays: Where you need to frequently add or remove elements.
· Storing Sequences: Such as the order of elements in a to-do list or playlist.
· Implementing Other Data Structures: Lists can be used as the building
blocks for stacks, queues, and more.
4.2.4 Tree: Best for Hierarchical Data
When to Use: Trees are essential when dealing with hierarchical data, where elements
are naturally organized in a parent-child relationship. Trees are used in:
· Hierarchical Databases: Representing organizational structures, file systems,
or XM- L/HTML documents.
114
www.OnlineMathAcademe.com
· Binary Search Trees (BSTs): For efficient searching, insertion, and deletion
operations.
· Understanding Code Structure: When building compilers, trees are used to
break down and understand the code's structure, helping the computer figure
out its step-by-step instructions.
4.2.5 Graph: Best for Networked Data
When to Use: Graphs are used when you need to represent a set of objects (nodes) and
the connections (edges) between them. Graphs are particularly useful in problems
involving networks, such as:
· Social Networks: Representing users and their connections (friends,
followers).
· Pathfinding Algorithms: Like finding the shortest path in maps or game
development.
· Dependency Resolution: Such as determining the build order of software
projects with interdependent components.
4.3 Combining Computational Structures for Complex
Problems
Combining different data structures, such as lists, stacks, queues, trees, and graphs, is
essential for solving complex problems effectively. Each of these structures has its own
strengths, and when we combine them, we can tackle more challenging problems with
greater success.
This combination allows us to create stronger and more efficient solutions. It helps us
manage complex data relationships and improve our ability to solve problems. By using
these structures together, we can develop solutions that are better suited to specific
needs and challenges, ultimately enhancing both performance and functionality.
4.3.1 Combining Stacks and Queues to Evaluate Expressions
Stacks and queues are powerful tools in evaluating mathematical expressions, especially
when the expressions involve complex operations. By combining these two data
structures, we can efficiently manage the order of operations, handle parentheses, and
ensure the correct evaluation of expressions.
4.3.2 Combining Stack and Graph to perform Depth-First Search
(DFS)
Depth-First Search (DFS) is a fundamental algorithm used to explore or traverse through
a graph or tree structure. It uses a stack data structure to keep track of the vertices or
nodes that need to be visited. This method is particularly useful when we need to explore
as far as possible along a branch before backtracking, making it ideal for situations
115
www.OnlineMathAcademe.com
where deep exploration is required.
Example: Consider the graph shown in Figure 4.13, as a tree with numeric nodes:
www.OnlineMathAcademe.com
7 has no children, nothing is added to the stack. The stack now contains node
[4].
8. Step 7: Pop the top of the stack (node 4). Mark node 4 as visited and push its
unvisited children (nodes 8, 9) onto the stack. The stack now contains nodes
[9, 8].
9. Step 8: Pop the top of the stack (node 8). Mark node 8 as visited. Since node
8 has no children, nothing is added to the stack. The stack now contains node
[9].
10. Step 9: Pop the top of the stack (node 9). Mark node 9 as visited. Since node
9 has no children, the stack is now empty.
The traversal order of the nodes using DFS in this example would be: 1, 2, 5, 6, 3, 7, 4, 8,
9.
In this example, the DFS algorithm starts at the root node (1) and explores as far as
possible along each branch before backtracking. By using a stack, the algorithm
traverses the graph depth-first, visiting nodes in the order: 1, 2, 5, 6, 3, 7, 4, 8, 9. The
stack helps manage the nodes to visit next, ensuring a complete exploration of each
branch before moving to the next.
4.3.3 Combining Queue and Graph to Perform Breadth-First Search
(BFS)
Breadth-First Search (BFS) is another fundamental algorithm used to explore or traverse
through a graph or tree structure. Unlike Depth-First Search, BFS uses a queue data
structure to keep track of the vertices or nodes that need to be visited. This method is
particularly useful when we need to explore all nodes at the present depth level before
moving on to nodes at the next depth level, making it ideal for situations where we need
to find the shortest path or explore all possible paths level by level.
Example: Consider the same graph represented in Figure 4.13, as a tree with numeric
nodes:
Here's how the BFS algorithm uses a queue to traverse this graph:
1. Start with an empty queue and enqueue the root node (1).
2. Step 1: Dequeue node 1 and mark it as visited. Enqueue all of its unvisited
children (nodes 2, 3, 4). The queue now contains nodes [2, 3, 4],
3. Step 2: Dequeue the front of the queue (node 2). Mark node 2 as visited and
enqueue its unvisited children (nodes 5, 6). The queue now contains nodes [3, 4,
5, 6],
4. Step 3: Dequeue the front of the queue (node 3). Mark node 3 as visited and
enqueue its unvisited child (node 7). The queue now contains nodes [4, 5, 6, 7],
5. Step 4: Dequeue the front of the queue (node 4). Mark node 4 as visited and
enqueue its unvisited children (nodes 8, 9). The queue now contains nodes [5, 6,
117
www.OnlineMathAcademe.com
7. 8, 9],
6. Step 5: Dequeue the front of the queue (node 5). Mark node 5 as visited. Since
node 5 has no children, nothing is added to the queue. The queue now contains
nodes [6, 7, 8, 9],
7. Step 6: Dequeue the front of the queue (node 6). Mark node 6 as visited. Since
node 6 has no children, nothing is added to the queue. The queue now contains
nodes [7, 8, 9],
8. Step 7: Dequeue the front of the queue (node 7). Mark node 7 as visited. Since
node 7 has no children, nothing is added to the queue. The queue now contains
nodes [8, 9].
9. Step 8: Dequeue the front of the queue (node 8). Mark node 8 as visited. Since
node 8 has no children, nothing is added to the queue. The queue now contains
node [9].
10. Step 9: Dequeue the front of the queue (node 9). Mark node 9 as visited. Since
node 9 has no children, the queue is now empty.
The traversal order of the nodes using BFS in this example would be: 1, 2, 3, 4, 5,
6, 7, 8, 9. In this example, the BFS algorithm, using a queue, guarantees that all
nodes at the current level of the tree or graph are explored before proceeding to
the next level. This approach is particularly effective for finding the shortest path
in unweighted graphs or exploring all possible connections at each level of
depth.
4.3.4 Combining List and Stack to Perform Sequential Operations
Lists and stacks are fundamental data structures that, when combined, provide a
powerful way to manage and process data in a controlled sequence. A list allows for
flexible data storage and access, while a stack imposes a Last-In-First-Out (LIFO) order,
making it useful for tasks where the most recent element needs to be processed first.
Example: Consider a scenario where we need to reverse the order of a list of numbers
using a stack. Let's take the following list of numbers as an example:
Original List: [10,20,30,40,50]
To reverse the order of this list using a stack, we can follow these steps:
1. Initialize an empty stack.
2. Step 1 : Push each element of the list onto the stack. After pushing all
elements, the stack will contain:
Stack: [10 20 30 40 50]
3. Step 2: Pop elements from the stack one by one and insert them back into
the list. Since the stack follows the LIFO order, the elements will be inserted in
reverse order.
4. Step 3: After all elements are popped and inserted back into the list, the list
118
www.OnlineMathAcademe.com
will now be:
Reversed List: [50,40,30,20,10]
In this example, the stack is used to temporarily hold the elements of the list, enabling us
to reverse the order by taking advantage of the LIFO nature of the stack. The
combination of a list and a stack allows us to efficiently perform operations that require
reversing, undoing, or backtracking, which are common in various algorithms and
applications.
Summary
This chapter offers a comprehensive overview of fundamental computational structures,
including lists, stacks, queues, trees, and graphs. It details their properties, operations,
and applications, emphasizing their roles in organizing and managing data. The chapter
also addresses the criteria for selecting appropriate data structures based on problem
requirements. Additionally, it explores the integration of different computational
structures to address complex problems effectively. By providing a detailed
understanding of these structures, the chapter aims to enhance the reader's ability to
apply them effectively in various computational contexts.
119
www.OnlineMathAcademe.com
4. When converting an infix expression to postfix notation, what does a stack
help to manage?
a) Order of operands
b) Priority of operators
c) Parentheses
d) Both b and c
5. Which operation is used to add an item to a queue?
a) Dequeue
b) Peek
c) Enqueue
d) Remove
6. In the context of Breadth-First Search (BFS) in a tree, which operation of queue
is used to visit nodes level by level?
a) Adding nodes to the end of a stack.
b) Removing nodes from the end of a list.
c) Enqueueing nodes to a queue.
d) Dequeueing nodes from a stack.
7. Which of the following tree traversals visits the root node before its children?
a) In-order
b) Pre-order
c) Post-order
d) Level-order
8. Which of the following is true about the height of a tree?
a) The height is the number of edges from the root to the deepest node
b) The height is the number of nodes from the root to the deepest node
c) The height is the number of children of the root node
d) The height is always equal to the number of nodes in the tree
9. Which graph traversal explores all immediate neighbors of a vertex before moving
to the next level?
a) Depth-First Search (DFS)
b) Breadth-First Search (BFS)
c) Depth-Limited Search (DLS)
d) Iterative Deepening Search (IDS)
10. For which scenario would a graph data structure be most appropriate?
a) Managing a to-do list
b) Modeling a line of customers in a store
c) Representing connections in a social network
120
www.OnlineMathAcademe.com
Short Questions
1. Explain how the ' extend() ' function works in python lists. Provide an example.
2. Explain the potential issues which could arise when two variables reference the
same list in a program? Provide an example.
3. Define a stack and explain the Last-In, First-Out (LIFO) principle.
4. How does the stack help in balancing parentheses in an expression? Describe
the process.
5. Differentiate between the Enqueue and Dequeue operations of queue.
6. Explain how the concept of a queue is applied in a computer's job scheduling
system?
7. How can lists be utilized to implement other data structures?
8. Differentiate between the Depth-First Search (DFS) and Breadth-First Search
(BFS).
Long Questions
1. Discuss the dynamic size property of lists in Python. How does this property
make lists more flexible?
2. Write a python program to manage a project's task list. Start with an initial list
containing the following tasks=[design, development, testing, deployment].
Perform the following operations on the tasks list:
· Add 'review' to the end of the list.
· Insert 'planning' at the third position in the list.
· Update 'testing' to quality assurance.
· Remove 'development ' from the list by its value.
· Remove the task at index 1 from the list.
· Find the index of the task 'deployment ' and print it.
· Print the final list after all modifications.
· Count and print the number of tasks in the list.
3. Discuss two real-world situations where stacks are commonly used.
Explain how stack operations function in these contexts.
4. Consider the following infix expression (5 + 2) * (3 - 1).
(a) Describe the step-by-step process to convert this infix expression
into postfix notation using a stack.
(b) Illustrate the state of the stack and the output list after processing
each token of the infix expression.
Hint: A token is a single element in an expression, such as a number,
operator, or parenthesis.
5. Write a Python code to simulate a queue of print jobs. The code perform
121
www.OnlineMathAcademe.com
following operations:
(a) Create an empty queue.
(b) Add three print jobs to the queue.
(c) Display the print job at the front of the queue without removing it.
(d) Remove the print job from the front of the queue.
(e) Add another print job to the queue.
(f) Display the updated queue of print jobs.
6. Explain the different types of tree traversals (In-order, Pre-order, Post-order).
Provide an example of each traversal using a given tree structure, and explain
how each traversal method processes the nodes.
Consider the following graph and perform the operations specified below:
Required Operations:
(a) Start from node A, write down the sequence of nodes visited during a
depth-first search traversal of the graph.
(b) Start from node A, write down the sequence of nodes visited
throughout a breadth-first search traversal of the graph.
8. Consider the task of organizing a desk. Describe how you can use both a stack
and a queue to manage tasks such as sorting papers, putting away books, and
cleaning the desk.
122
www.OnlineMathAcademe.com
UNIT
Data Analytics
5
Student Learning Outcomes
By the end of this chapter, students will be able to:
· understand the role and importance of model building and their real world
applications
· build basic statistical models for real world problems and test their performance
· understand and explain experimental design in data science
· explain the types, uses, methods of data visualizations,
· understand the benefits of visualizing data through descriptive statistics
· explain and create a data visualization using data visualization software (for
example MS Excel, Google Sheets, Python, Tableau, or Matplotlib).
123
www.OnlineMathAcademe.com
Introduction
Model building is the process of creating simplified representations of complex
problems. It helps in understanding, analyzing, and solving real-world issues by
focusing on key elements.
5.1 Model Building
5.1.1 Definition and Importance of Models
In simple terms, a model is a simplified way of looking at a complex problem or situation.
It helps to understand, explain, or predict how things work. Just like a map helps
someone navigate a city by showing roads and landmarks, a model helps us understand
a problem by focusing on the most important parts and leaving out unnecessary details.
Example: Consider a student preparing for exams. To decide how much time to spend on
each subject, the student creates a study plan. This plan is a model that simplifies their
schedule by focusing on important subjects and ignoring less relevant tasks.
5.1.2 Role of Models in Decision-Making
Models are useful because they give a structured way to think about a problem. They
take complicated information and make it easier to work with. This is especially
important in decision making, where models help us consider different outcomes
before making a choice.
Example: When a farmer use a model to decide the best time to plant crops. By studying
weather patterns and soil conditions, the model helps the farmer predict the right
planting time, which increases the chances of a good harvest.
www.OnlineMathAcademe.com
5.2 Basic Statistical Concepts
Statistics is a branch of mathematics that helps us understand and analyze data. By using
statistics, we can summarize large sets of information in a simple way, making it easier to draw
conclusions. Some basic statistical concepts are descriptive statistics, measures of central
tendency, measures of dispersion, and probability.
5.2.1 Measures of Central Tendency
Measures of central tendency help us find the “center” or typical value in a set of data. There are
three main measures of central tendency: mean, median, and mode. These measures give us a
sense of the average or most common values in a dataset.
Mean
The mean is the average of all the numbers in a data set. To find the mean, we add all the numbers
together and divide by the total number of values.
Example: Imagine 5 students scored 50, 60, 70, 80, and 90 in a test. The mean score is calculated by
adding all the scores and then dividing by the number of students: This helps us understand the
general performance level of the group.
Median
The median is the middle value when the numbers are arranged in order. If there is an odd
number of values, the median is the exact middle number. If there is an even number of values,
the median is the average of the two middle numbers.
Example: Using the same test scores: 50, 60, 70, 80, and 90. When we arrange these scores in
ascending order (which they already are), the middle value is 70. Therefore, the median score is
70. Example with Even Numbers: If the scores were 50, 60, 70, and 80, we would take the average
of the two middle scores (60 and 70):
Median = (60+70)/2= 65, the median is 65.
The median helps us understand the middle point of the data.
Mode
The mode is the number that appears most often in a data set. There can be more than one mode
if multiple numbers appear with the same highest frequency.
Example: If 5 students scored 50, 60, 70, 70, and 90, the number 70 appears twice, while all other
numbers appear only once. Therefore, the mode is 70.
Example with Multiple Modes: If the scores were 50, 60, 70, 70, 60, and 90, both 60 and 70 appear
twice. So, there are two modes: 60 and 70.
The mode helps us identify the most frequent or common value in the data.
5.2.2 Descriptive Statistics
Descriptive statistics are used to summarize and organize data. Instead of looking at every
individual piece of data, descriptive statistics give us a way to see the overall picture.
Example: Imagine a group of 10 college students takes a math exam, and their scores are: 50, 65,
75, 80, 85, 90, 95, 60, 70, and 88.
To summarize this data:
125
www.OnlineMathAcademe.com
· Mean (Average): The mean score is calculated by adding all the scores and dividing by
the number of students.
· Mean = (50 + 65 + 75 + 80 + 85 + 90 + 95 + 60 + 70 + 88)/10= 75.5
· Highest and Lowest Scores: The highest score is 95, and the lowest score is 50.
These simple calculations give us a quick summary of how the students performed, without
needing to look at each individual score in detail.
5.2.3 Measures of Dispersion
Measures of dispersion tell us how spread out or scattered the data is. Two common measures of
dispersion are variance and standard deviation. These help us understand whether the data
points are close to the average (mean) or far from it.
Variance
The variance shows how much the numbers in a data set differ from the mean. A higher variance
means that the numbers are more spread out, while a lower variance means that the numbers are
closer to the mean. To calculate variance, we use the following mathematical formula.
N
1
s2 = å (x 1 - m )2
N t =1
Where: xi represents each individual value in the data set, µ is the mean of the data
set, N is the total number of values in the data set.
Example: Imagine two classes, Class A and Class B, took the same exam.
1. In Class A, the scores are: 50, 52, 55, 57, and 60.
2. In Class B, the scores are: 30, 45, 55, 75, and 90.
Steps are involved in variance calculations:
Step 1: Variance for Class A
Given Score = 50,52,55,57,60
Step 1.1: Compute the Mean (μ)
(μ) = 50 +52 +55 +57 + 60 = 274 =54.8
5 5
Step 1.2: Compute Each Squared Deviation ((xi−μ2)
xi xi−μ (xi−μ)2
50 50−54.8=−4.8 23.04
52 52−54.8=−2.8 7.84
55 55−54.8=0.2 .04
57 57−54.8=2.2 4.84
60 60−54.8=5.2 27.04
126
www.OnlineMathAcademe.com
Step 1.3: Compute Variance
σ2 = 23.04+7.84+0.04+4.84+27.04
5
62.8/5 = 12.56
Step 2: Variance for Class B
Given Scores: 30,45,55,75,90
μ = 30+45+55+75+90 = 295 = 59
5 5
xi xi−μ (xi−μ)2
30 30−59 = −29 841
45 45− 59 = −14 196
55 55 – 59 = − 4 16
75 75 – 59 = 16 256
90 90 – 59 = 31 961
Step 2.3: Compute Variance
2
σ = 841 +196 +16 +256 +961
5
= 2270/ 5 = 454
· Variance of Class A: 12.56
· Variance of Class B: 454
This confirms that Class B has a much higher variance, meaning the scores are more
spread out compared to Class A.
5.2.3.2 Standard Deviation
The standard deviation is similar to variance but provides a more practical number. It
tells us how spread out the numbers are in relation to the mean. The standard deviation
is simply the square root of the variance. To calculate standard deviation, we use the
following mathematical formula.
N
1
s = å (x 1 - m )2
N t =1
Where: - xi represents each individual value in the data set, - µ is the mean of the data set,
- N is the total number of values in the data set.
Calculating Standard Deviation:
Class A:
Standard 12.56 Deviation = 3.55
127
www.OnlineMathAcademe.com
Class B:
Standard 456 Deviation = 21.26
The standard deviation for Class A is approximately 3.55, while for Class B, it is about
21.26. This means that Class A's scores are closely packed around the mean, whereas
Class B's scores are more widely scattered. The standard deviation helps us easily
understand how much variation there is in the scores.
5.2.4 Introduction to Probability
Probability is the study of how likely an event is to happen. It helps us predict outcomes
based on what we know.
Example: Consider flipping a coin. There are two possible outcomes: heads or tails. Since
both outcomes are equally likely, the probability of getting heads is 50% (or 1/2), and the
probability of getting tails is also 50%.
We can express this mathematically as:
www.OnlineMathAcademe.com
For illustration, you can use the following sample data: 3, 5, 8, 8, 10, 12, 15, 15, 16, 18. But
if you are interested in collecting real data from your classmates, you are welcome to do
so.
www.OnlineMathAcademe.com
4. What influences your purchasing decisions the most? (e.g., price, quality,
availability)
5. Any additional comments or suggestions?
Responses collected from 50 customers over the weekend.
5.3.1.2 Observations
Observation involves collecting data by watching or monitoring subjects in their natural
environment. This method is useful when researchers want to gather data on behaviors
or phenomena without interference.
Example: A restaurant is interested in knowing which tables are most frequently chosen
by customers during lunchtime. A staff member observes the seating choices over a
period of one week. Based on this observation, the restaurant arranges its seating to
optimize the comfort and flow of customer traffic, which helps in improving customer
satisfaction and service efficiency.
5.3.1.3 Experiments
Experiments involve manipulating one or more variables to determine their effect on
another variable. This method is particularly useful in scientific and engineering fields
where controlled environments are necessary for accurate measurement.
Example: A school teacher wants to test whether providing students with printed notes
helps improve their performance in exams. The teacher conducts an experiment with
two groups of students, one receiving printed notes and the other relying solely on
lectures. After one month, both groups take the same test, and the teacher compares
the results to see if printed notes had a positive impact on performance.
5.3.2 Data Preparation
Once data has been collected, it is important to prepare it for analysis. This includes
cleaning the data to remove errors or inconsistencies, organizing it in a meaningful way,
and converting it into a format suitable for analysis. In cases where data is missing or
incorrect, researchers may need to employ techniques such as interpolation or statistical
adjustments to ensure accuracy.
Example: If survey responses contain incomplete information, missing values can be
estimated based on the available data. Proper data preparation ensures that the analysis
leads to reliable and valid results.
5.3.3 Data Cleaning and Transformation
Data cleaning and transformation are important steps to prepare data for analysis. Raw
data often has errors, missing values, or may be in the wrong format. To ensure accurate
results in analysis, it is important to fix these issues before moving forward.
5.3.3.1 Data Cleaning
Data cleaning means correcting or removing any problems in the data. These problems
can include incorrect entries, missing values, or duplicate data. If these errors are not
130
www.OnlineMathAcademe.com
fixed, the results of the analysis will be misleading.
Example: Imagine a school collecting data on student grades. Some students may have
entered their names incorrectly, or a few grades may be missing from the records. In this
case, data cleaning would involve correcting any wrong names and finding the missing
grades to complete the dataset. Figure 5.2, illustrates the data cleaning process for
student grades in a school. It shows examples of common issues such as incorrect
names, missing grades, and duplicate entries.
5.3.3.2 Data Transformation
Once the data is clean, it is often necessary to transform it into a format that is easy to
work with. This transformation may include converting data into different formats,
creating new columns, or organizing data in a different way. These changes help make
the data more suitable for analysis or modeling.
Example: After cleaning the student grade records, it may be necessary to transform
this data for better analysis. For instance, instead of displaying grades for each individual
student, the data
Original Data (with Errors)
Name Grade Class Section
Ali 85 10 A
Alie 90 10 A
Sara 10 A
www.OnlineMathAcademe.com
1. Imputation: One common method is to estimate the missing value using
existing data. Example: The school can calculate the average grade of all
students in Sara's class. If the average grade is 82, the school may assign this
value to Sara's record temporarily. This approach allows the school to maintain a
complete dataset while making a reasonable assumption about Sara's
performance.
2. Flagging: The school can also keep track of Sara's missing grade by adding a
note in the dataset. This method indicates that Sara's grade is not available,
making analysts aware of the incomplete data. This approach ensures
transparency while allowing the analysis to proceed without filling in the gap.
3. Removal: If the number of missing entries is small, the school might choose to
exclude Sara's record from specific analyses. This decision is acceptable if it does
not significantly impact the overall understanding of student performance.
However, it risks losing valuable information about Sara.
5.4 Building Statistical Models
In this section, we will explore the basic building blocks of statistical models, including
different types of models, how they are developed, and how to evaluate their
performance. We'll also look at real-world examples to make the concepts easy to
understand.
5.4.1 Introduction to Statistical Modeling
Statistical modeling is a way to use data to make sense of the world and predict what will
happen in the future. Think of it like this: if you want to know how much money you'll
spend on groceries next month, you can look at what you spent in the past. By analyzing
that data, you can create a model to help you estimate your future grocery expenses.
Example: If you usually spend around 10,000 rupees each month, but your expenses
fluctuate, a statistical model can take into account factors like your family size or special
occasions. This way, you can get a better idea of how much you may need to budget for
your groceries of next month.
5.4.1.1 Model Development
Building a statistical model involves several steps. Let's break them down:
· Step 1: Define the Problem
First, we need to understand the problem. Example: If we are trying to predict
grocery expenses, we need to know which factors will cause to increase our
grocery expenses (e.g., family size, location, or income).
· Step 2: Collect Data
Next, we gather data related to the problem. In our example, we will collect data
on past spending habits, number of family members, and any other factors that
may affect grocery costs.
132
www.OnlineMathAcademe.com
· Step 3: Choose an Algorithm
Based on the problem and the data, we choose an algorithm. Algorithms are
methods that help us create a model. Some popular algorithms are linear
regression and logistic regression, which we will further in this section.
· Step 4: Train the Model
The model is then trained using the data. This means the model learns from the
data to make predictions.
· Step 5: Evaluate the Model
Finally, we test the model to see how well it works by using new data. This step is
very important to ensure the model makes good predictions.
5.4.1.2 Linear Regression
Linear regression is a common statistical model used to understand the relationship
between two variables. It is often used to predict one variable based on another. Let's go
through a practical example to explain how it works.
Example: Imagine you run a small fruit stall in your town, and you want to predict how
much money you will make each day based on the number of customers who visit your
stall. The number of customers is the independent variable (the cause), and the money
you earn is the dependent variable (the effect). We will use linear regression to
understand this relationship and help you predict future earnings.
· Step 1: Collecting Data
To build a linear regression model, we need data. Let's assume you've recorded
the number of customers and your daily earnings for the last 5 days:
Here, the number of customers is our independent variable (X), and the daily earnings
are the dependent variable (Y ).
· Step 2: Understanding the Linear Regression Formula
The formula for simple linear regression is:
Y =β0+β1x+ϵ
Where:
– Y is the dependent variable (in our case, daily earnings),
– X is the independent variable (the number of customers),
– β0 is the intercept, which is the starting value of Y when X = 0,
133
www.OnlineMathAcademe.com
– β1 is the slope, which shows how much Y changes with each unit
increase in X,
– ε is the error term, which accounts for the difference between the
predicted and actual values.
· Step 3: Building the Linear Regression Model
When building a linear regression model, our goal is to find the best line that
explains how two things are related in this case, the number of customers and
daily earnings. Here's how we get the values for the slope (40) and intercept
(300):
Understanding the Slope (β1 = 40)
The slope shows how much extra money we make for every new customer. Let's
use our data to figure it out:
If you notice, for every 5 extra customers, earnings go up by 200 rupees. So, for each new
customer:
β1 = 200/ 5 = 40
This means every new customer adds 40 rupees to our earnings.
Understanding the Intercept (β0 = 300)
The intercept (β0) represents the earnings when no customers visit. To find this value, we
look at where the line crosses the vertical axis when the number of customers is zero. In
simpler terms, it tells us what the base earnings are, even if no one shows up.
Let's look at the data:
134
www.OnlineMathAcademe.com
Using this data, we calculate the slope (β1 = 40) means for every additional customer,
earnings increase by 40 rupees. Now, to find the intercept, we need to consider how
much we earn when there are no customers.
We can use the equation:
Earnings = β0 + β1 × Customers
If we take any data point, say when there are 10 customers, the earnings are 500 rupees.
Substituting these values into the equation:
500 = β0 + (40 × 10)
500 = β0 + 400
Solving this gives:
β0 = 500 − 400 = 100
This means that, based on the data, if no customers show up, you'd still expect to make
100 rupees, maybe from regular customers or other fixed earnings. So, the intercept
value of 100 rupees represents the minimum amount you'd make on a day with zero
customers.
· Final Equation:
Earnings = 100 + 40 x Customers
This equation means:
– You'll always earn 100 rupees, even if no one comes.
– Each new customer adds 40 rupees to your total.
· Step 4: Interpreting the Model
Once the model is built, we can use it to predict future earnings. For example, if
you expect 22 customers tomorrow, the predicted earnings would be:
www.OnlineMathAcademe.com
To improve your statistical model, consider these suggestions:
1. Use more data points for better accuracy.
2. Include relevant factors like family size or special events that may affect spending's.
3. Regularly update your model with new data to keep it relevant.
4. Test your predictions against actual spending to refine your approach.
www.OnlineMathAcademe.com
In this equation:
– P(Pass) is the probability of passing the exam.
– e is the base of the natural logarithm.
– β0 is the intercept of the model, which represents the log-odds of
passing when no hours are studied.
– β1 is the coefficient for the number of hours studied, showing how
much the log-odds of passing changes with each additional hour.
· Interpreting the Coefficients:
After fitting the model to our data, suppose we find:
Here, β0 = 1 and β1 = 0.6. This means that for each hour studied, the
likelihood of passing
the exam increases. If a student studies for 5 hours, we can calculate their
passing probability:
P(Pass) = 1 1 + e−(1+0.6×5) ≈ 0.83This means there is an 83% chance that
the student will pass after studying for 5 hours.
· Testing the Model:
Once the model is built, we can use it to make predictions. Let's say a new
student studies for 4 hours. We can use our model to find the probability of
passing:
137
www.OnlineMathAcademe.com
Student Math Score English Score
Basim 85 70
Umer 90 65
Anie 50 80
Tallat 40 85
Maliha 60 60
We can use clustering to group these students based on their performance in these two
subjects. K-means Clustering
K-means clustering is one of the simplest and most popular techniques to group data. In
K-means, we need to decide how many groups (clusters) we want. For this example, let's
say we want to divide the students into two clusters: one for students who are strong in
math and one for students who are strong in English. The algorithm will group students
with similar performance in math and English together by calculating the distance
between their scores and finding patterns. It will assign students like Basim and Umer
(who are good at math) to one group and students like Anie and Tallat (who are good at
English) to another group.
Step-by-step Working of K-means:
138
www.OnlineMathAcademe.com
After calculating these distances, we assign each student to the nearest center.
Based on the calculations:
1. Basim and Umer are closer to Center 1 (Basim), so they join Cluster 1 (Math-
strong).
2. Anie, Tallat, and Maliha are closer to Center 2 (Tallat), so they join Cluster 2
(English-strong).
· Step 4: Recalculate the centers.
Now that the students have been assigned to clusters, we need to recalculate the
centers by finding the average position (average scores) of the students in each
cluster.
139
www.OnlineMathAcademe.com
· Step 5: Repeat steps 3 and 4 until the centers stop moving.
Now that the centers are updated, we will again calculate the distance between
each student and the new centers and reassign them if needed. This process
continues until the centers no longer change, which means the clusters are
stable.
For this example, after recalculating, the cluster centers are already quite stable.
Basim and Umer still be closer to the math-strong cluster, and Anie, Tallat, and
maliha would remain in the English-strong cluster.
After these steps, we will get two clusters: Cluster 1: Basim, Umer, and Maliha
(good in math) Cluster: 2 Anie and Tallat (good in English)
5.4.2 Evaluating and Interpreting Models
Once a model is built, it is important to check how well it performs and to
understand the results it provides. This is called model evaluation.
5.4.2.1 Performance Metrics
Performance metrics help us measure how well a model is doing. Some common metrics
include:
• Error Metrics
Error metrics measure how much the model's predictions differ from the actual
values. In our grocery example, if the model predicts a monthly grocery bill of
8,000 rupees but the actual bill is 10,000 rupees, the difference is the error.
• Accuracy Metrics
Accuracy metrics tell us how many of the model's predictions were correct. For
example, if a model predicts whether a student will pass or fail an exam, accuracy
measures how often the model was right.
5.4.2.2 Interpreting Outputs
Interpreting a model's output means understanding what the results tell us.
· Drawing Conclusions from Insights
For example, if our linear regression model shows that hours studied strongly
affect exam scores, we can conclude that students should study more hours to
improve their scores.
5.4.2.3 Ethical Considerations
When building models, it is important to consider the ethical implications, such as
fairness and privacy.
· Fairness and Bias
A model should be fair and not biased. For example, if a model is used to decide
who gets a loan, it should not unfairly favor one group of people over another.
· Data Privacy
When using personal data to build models, it is important to respect privacy. For
140
www.OnlineMathAcademe.com
example, if a company is using customer data to build models, they should
ensure the data is secure and not shared without permission.
Always visualize your data before building models and test your results on new data for
better accuracy.
Class Activity
Linear Regression
You are given the following data that shows the relationship between the
number of hours studied and the marks obtained in a test by students. Your
task is to build a linear regression model that predicts the marks based on the
number of hours studied.
Hours Marks Obtained
1
Studied 20
2 25
3 35
4 40
5 45
6 50
Steps:
1. Plot the data points on a graph (Hours studied on the x-axis and Marks
obtained on the y-axis).
2. Calculate the equation of the line using linear regression.
3. Use the equation to predict the marks for a student who studied for 7
hours.
4. How well does the model fit the data? Justify your answer by calculating
the error between actual and predicted marks.
Class Activity
Logistic Regression
You are a college administrator, and you want to predict whether students will
pass or fail a final exam based on their midterm marks. The following data
shows the midterm marks of students and whether they passed or failed the
final exam. Your task is to build a logistic regression model to predict the
likelihood of passing based on midterm marks.
141
www.OnlineMathAcademe.com
Class Activity
Midterm Marks Pass (1) / Fail (0)
30 0
40 0
50 0
60 1
70 1
80 1
90 1
Steps:
1. Plot the data points (Midterm marks on the x-axis, and Pass/Fail on
the y-axis).
2. Fit a logistic regression model to the data.
3. Based on the model, predict the probability of passing for a student
who scored 55 in the midterm.
4. Discuss how the logistic regression model helps in making this
prediction and whether it's accurate.
Class Activity
K-Means Clustering
You work in a local retail shop, and you want to segment your customers into
two groups based on their monthly spending in two categories: groceries and
clothing. The following table shows the monthly spending of six customers.
Your task is to use K-means clustering to group these customers into two
clusters based on their spending habits.
Customer Groceries Spending (in Clothing Spending (in $)
Customer 1 150
$) 100
Customer 2 200 150
Customer 3 100 50
Customer 4 80 20
Customer 5 160 90
Customer 6 40 10
Steps:
1. Choose K = 2 clusters and randomly select two initial cluster centers.
2. Assign each customer to the nearest cluster based on their spending.
3. Recalculate the cluster centers by finding the average spending in each
category for each cluster.
4. Repeat the process until the cluster centers stabilize.
5. Analyze the clusters and describe the spending habits of customers in
each group.
142
www.OnlineMathAcademe.com
5.4 Introduction to Data Visualization
Data visualization is the process of representing data in a visual format, such as graphs or charts.
It helps us to quickly grasp patterns, trends, and insights from data.
5.5.1 Types of Visualizations
Data visualization is a powerful way to understand complex information. Different types of
visualizations serve various purposes, making it easier to interpret and analyze data. Below are
some common types of visualizations explained in detail:
5.5.1.1 Bar Charts
Bar charts are ideal for comparing different categories. Each bar represents a category, and the
height (or length) of the bar indicates the value associated with that category.
Example: Imagine you want to compare the sales figures for different products in a store. A
bar chart can visually represent this data.
Sales on Day 1 and Day 2 for various items
www.OnlineMathAcademe.com
5.5.1.3 Histograms
Histograms are used to show the distribution of a dataset. They group data into bins
or intervals, allowing you to see how frequently values occur within those ranges.
Example: If you want to analyze how students performed in an math exam, a
histogram can show the distribution of scores.
Maltis Test Results
5.5.1.4 Scatterplots
Scatterplots display relationships between two variables. Each point represents an
observation, and the position on the graph indicates values for both variables.
Example: A scatterplot can be used to explore the relationship between the number of
hours studied and exam scores.
Hours
Figure 5.7: Scatterplot showing the relationship between hours studied and exam scores
144
www.OnlineMathAcademe.com
5.5.1.5 Boxplots
Boxplots, or whisker plots, summarize data distribution by displaying the median,
quartiles, and potential outliers. They provide a visual summary of data variability.
Example: A boxplot can be used to compare the exam scores of different classes to see
which class performed better overall.
www.OnlineMathAcademe.com
had the most sales.
5.6.2 Creating and Interpreting Visualizations
Step-by-Step Guide: Here's a simple guide to creating a visualization in Excel or Google
Sheets.
1. Enter Your Data: Start by entering your data into the spreadsheet. Example: In
one column, you could have the months (January, February, etc.), and in another
column, the sales figures for each month.
2. Select the Data: Highlight the data you want to visualize by clicking and
dragging your mouse over the cells.
3. Choose a Chart Type: Click on the "Insert" tab and select the type of chart you
want to create (bar chart, line graph, etc.).
4. Customize the Chart: You can add labels to your chart to make it clearer, such
as labeling the x-axis with the months and the y-axis with the sales figures. This
makes the chart easier to interpret.
5. Understanding Statistical Representations:
When you create a visualization, it's important to understand what the chart is
telling you.
Example: Bar Charts: Useful for comparing different categories, such as monthly sales.
Line Graphs: Ideal for showing trends over time, like how sales have increased or
decreased over several months.
Summary
This unit focuses on model building and data visualization, equipping learners with
the skills to analyze, interpret, and present data effectively. Key topics include:
1. Model Building:
o Understand the role and importance of statistical models in solving real-
world problems.
o Learn to build basic statistical models (e.g., linear regression) and evaluate
their performance using appropriate metrics.
2. Experimental Design:
o Gain an understanding of experimental design in data science, including
hypothesis testing, control groups, and randomization.
3. Data Visualization:
o Explore the types and uses of data visualizations (e.g., bar charts, scatter
plots, heatmaps).
146
www.OnlineMathAcademe.com
o Learn methods for creating effective visualizations to communicate insights
clearly.
4. Descriptive Statistics:
o Understand the benefits of visualizing data through descriptive statistics
(e.g., mean, median, standard deviation) to summarize and interpret data
trends.
5. Tools for Visualization:
o Develop hands-on skills in creating visualizations using tools like MS Excel,
Google Sheets, Python (Matplotlib), and Tableau.
147
www.OnlineMathAcademe.com
b) The change in the dependent variable for a unit change in the independent
variable
c) The error term
d) The mean of the data
6. Which of the following is an example of a real-world application of statistical
models?
a) Predicting house prices
b) Creating social media posts
c) Designing websites
d) Writing essays
7. Which of the following is NOT a benefit of data visualization?
a) Identifying trends and patterns
b) Communicating insights effectively
c) Making data more complex
d) Summarizing large datasets
8. What is the primary goal of K-Means Clustering?
a) To classify data into predefined categories
b) To group data into clusters based on similarity
c) To predict continuous outcomes
d) To reduce the dimensionality of data
9. In K-Means Clustering, what does the "K" represent?
a) The number of features in the dataset
b) The number of clusters to be formed
c) The number of iterations required for convergence
d) The number of data points in the dataset
Short Questions
1. What is the importance of building statistical models in real-world
applications?
2. Name one basic statistical model used for predicting outcomes and explain
its purpose.
3. List two types of data visualizations and describe when you would use each.
4. How does visualizing data help in understanding descriptive statistics?
5. What is the purpose of using tools like MS Excel for data visualization?
6. Give an example of a real-world problem where a statistical model could be
applied.
148
www.OnlineMathAcademe.com
Long Questions
1. Explain the role and importance of statistical models in solving real-world
problems.
2. Describe the steps involved in building a basic statistical model (e.g., linear
regression). Include details on data collection, model training, and evaluation.
3. Discuss the types of data visualizations and their uses.
4. Explain the concept of model evaluation in statistical modeling.
5. Explain the K-Means Clustering algorithm step by step. Include details on how
initial centroids are selected, how data points are assigned to clusters, and how
centroids are updated.
6. Describe a real-world scenario where K-Means Clustering can be applied.
Explain how you would preprocess the data, choose the value of K, and interpret
the results.
149
www.OnlineMathAcademe.com
UNIT
Emerging Technologies
6
Student Learning Outcomes
By the end of this chapter, students will be able to:
· Understand the basic concepts of cloud computing, including virtualization, scalability,
and on-demand access.
· Identify and explain the different types of cloud services: Infrastructure as a Service
(laaS), Platform as a Service (PaaS), and Software as a Service (SaaS).
· Describe various cloud deployment models, such as public, private, hybrid, and multi-
cloud, and compare their features.
· Recognize the core principles of blockchain technology and the role of peer-to-peer
networks in its functioning.
· Explain the applications of blockchain in real-world scenarios, including
cryptocurrencies, smart contracts, and product tracking.
· Discuss the implications of cloud computing and blockchain, especially in areas like
data security and resource management.
· Explore future trends and innovations in cloud computing and blockchain, including
edge computing and Blockchain 2.0.
150
www.OnlineMathAcademe.com
Introduction
In the rapidly evolving landscape of technology, new paradigms and innovations are
continuously reshaping the way we interact with the digital world. This chapter explores
two of the most transformative technologies of our time: Cloud Computing and
Blockchain.
We begin by exploring the fundamentals of Cloud Computing, including its core
concepts such as virtualization, scalability, and on-demand access. We will also examine
the various types of cloud services like Infrastructure as a Service (laaS), Platform as a
Service (PaaS), and Software as a Service (SaaS), as well as different cloud deployment
models including public, private, hybrid, and multi-cloud environments. Understanding
these foundational elements will provide insights into the practical applications and
implications of cloud computing in various industries.
Following this, we shift our focus to Blockchain Technology, starting with its basic princi-
ples and components, such as the peer-to-peer network that forms the backbone of
blockchain's decentralized architecture. We will explore the use cases of blockchain,
including its role in cryptocurrencies and smart contracts, and discuss the applications
and implications of blockchain in areas like product tracking, financial services, and data
security.
The chapter concludes with a look into future trends and innovations within these
technologies, including edge computing, serverless architectures, and the next
generation of blockchain, often referred to as Blockchain 2.0 and beyond.
6.1 Definition and Overview of Emerging Technologies
Emerging technologies are new tools, systems, and methods that are currently being
developed or have just started to be used. These technologies have the potential to
change the way we live, work, and interact with the world. Here are some of the key
emerging technologies:
· Artificial Intelligence (AI): AI refers to machines and software that can think and
learn like humans. AI can help with tasks like recognizing faces, understanding
speech, and making decisions. It's used in everything from smart assistants like Siri to
self-driving cars.
· Cloud Computing: Cloud computing allows people to store and access data and
applications over the internet instead of on a local computer or server. This makes it
easier to share information, collaborate on projects, and scale up services without
needing expensive hardware. Examples include services like Google Drive, Dropbox,
and Amazon Web Services (AWS).
· Blockchain: Blockchain is a secure way to record and share information across many
computers, making it almost impossible to change or hack. It's best known for being
the technology behind cryptocurrencies like Bitcoin, but it's also used in other areas
151
www.OnlineMathAcademe.com
like supply chains and contracts.
· Internet of Things (loT): loT connects everyday objects, like refrigerators, cars, and
even clothes, to the internet. This allows them to send and receive data, making our
lives more convenient. For example, a smart thermostat can learn your schedule and
adjust the temperature in your home automatically.
· Augmented Reality (AR) and Virtual Reality (VR): AR adds digital elements to the
real world using devices like smartphones or glasses. VR creates a completely virtual
environment that you can interact with using special equipment. These technologies
are used in gaming, education, and training.
· 5G Technology: 5G is the next generation of wireless technology, offering much
faster internet speeds and more reliable connections. This will enable better
performance for mobile phones, smart devices, and even new technologies like
augmented reality (AR) and virtual reality (VR).
· Quantum Computing: Quantum computers use the principles of quantum physics
to process information much faster than traditional computers. They have the
potential to solve very complex problems that are currently impossible for regular
computers to handle.
· Biotechnology: Biotechnology involves using living organisms, like bacteria and
plants, to create new products or solve problems. For example, scientists are using
biotechnology to develop new medicines, improve crops, and even create
environmentally friendly materials.
6.2 Cloud Computing
Cloud computing is a model that allows easy and convenient access to computing
resources like servers, storage, and applications over the internet. These resources can
be quickly provided and released with minimal management effort or service provider
interaction. Cloud computing is like having a powerful computer that you can access
over the internet. Instead of buying and maintaining your own expensive computers and
storage devices, you can use cloud services to store data, run applications, and manage
your computing needs. This makes it easier and cheaper to get things done, as you can
use as much or as little of the service as you need, and you only pay for what you use. It's
like renting a supercomputer that you can use whenever you need it, from anywhere in
the world.
6.2.1 Basic Concepts of Cloud Computing
Cloud computing encompasses several basic concepts that are foundational to its
functionality and benefits.
6.2.1.1 Virtualization
Virtualization is a technology that allows a single physical machine to run multiple
virtual machines. It is like having a magic trick that lets one physical computer act like
152
www.OnlineMathAcademe.com
many separate computers. Imagine you have a single powerful computer, but with
virtualization, you can create several “virtual” computers inside it. Each of these virtual
computers can run its own operating system and applications as if they were
independent machines. This helps make better use of the hardware, reduces costs, and
allows for easier management and flexibility.
It's like turning one computer into many, making it possible to do more with less.
6.2.1.2 Scalability and Elasticity
Scalability and elasticity are important concepts in cloud computing that help manage
resources efficiently.
Scalability means you can add more resources when you need them. For example,
imagine you run an online store that usually has a steady number of visitors. However,
during busy times like Eid or 14th August sales, you get a huge spike in traffic. With
scalability, you can add more servers to handle this increased traffic, ensuring your
website runs smoothly without slowing down or crashing.
Elasticity takes this a step further by allowing the system to automatically adjust
resources based on the current demand. For instance, using the same online store
example, if your website starts getting a lot of traffic, the cloud service can automatically
add more servers to handle the load. When the traffic decreases after the sale, the
system can reduce the number of servers, so you're not paying for resources you don't
need. This automatic adjustment helps keep your website running efficiently and cost-
effectively.
6.2.1.3 On-Demand Access
On-demand access means that you can use computing resources whenever you need
them, without waiting for a long setup process. This is like being able to turn on a tap to
get water whenever you want, instead of having to dig a well first.
Example: Imagine you are working on a school project and suddenly need extra storage
space to save your files. With on-demand access, you can instantly rent additional
storage from a cloud provider and start using it right away. This saves time and effort,
allowing you to focus on your project instead of worrying about storage.
Difference with Elasticity:
· On-Demand Access: Focuses on the ability to obtain and use resources instantly
whenever needed.
· Elasticity: Focuses on the automatic adjustment of resources based on real-time
demand to maintain performance and efficiency.
6.2.2 Types of Cloud Services
There are different types of cloud services that cater to various needs. Cloud services are
typically categorized into three main types: Infrastructure as a Service (laaS), Platform as
a Service (PaaS), and Software as a Service (SaaS). Each type offers different levels of
153
www.OnlineMathAcademe.com
control, flexibility, and management, catering to various needs and use cases.
6.2.2.1 Infrastructure as a Service (laaS)
laaS offers basic computing infrastructure such as servers, storage, and networking on a
pay-as- you-go basis. Users have control over the operating systems, applications, and
storage, but not the underlying physical infrastructure.
Example: Amazon Web Services (AWS) allows users to rent virtual servers to run their
applications. Microsoft Azure and Google Compute Engine are other popular laaS
providers.
6.2.2.2 Platform as a Service (PaaS)
PaaS offers a complete development and deployment environment in the cloud. It
includes infrastructure (servers, storage, and networking), middleware, development
tools, and management services. Developers can focus on coding and deploying
applications without managing the hardware and software layers.
Example: Google App Engine allows developers to build and deploy applications using
a variety of programming languages. Other examples include Microsoft Azure App
Services and Heroku.
6.2.2.3 Software as a Service (SaaS)
SaaS provides access to software applications that are hosted and managed by the
service provider. Users simply subscribe to the service and use it over the internet. This
model is convenient for end-users as it requires no hardware management or software
updates. Example: Google Workspace (formerly G Suite) includes applications like
Gmail, Google Docs, and Google Drive. Other examples are
Microsoft Office 365 and Salesforce.
www.OnlineMathAcademe.com
Salesforce is one of the leading SaaS providers, known for its
customer relationship management (CRM) platform. It helps
businesses manage customer data, track sales, and automate
marketing tasks. Over 150,000 companies use Salesforce to
streamline their business processes and improve customer
satisfaction.
Class Activity
Research and identify a cloud service provider (e.g„ AWS, Azure, Google Cloud)
and describe how its services are used in a real-world scenario. Present your
ndings to the class.
155
www.OnlineMathAcademe.com
applications to the public cloud to handle increased load, while keeping critical data
secure in the private cloud.
6.2.3.4 Multi-Cloud
A multi-cloud approach uses multiple cloud services from different providers. This
model helps avoid dependency on a single provider and can enhance reliability and
performance.
Example: A company might use Google Cloud Platform for its data analytics, Microsoft
Azure for its enterprise applications, and Amazon Web Services for its backup and
disaster recovery. This ensures that if one provider experiences issues, the company can
still rely on other services.
6.2.4 Comparing Deployment Models
Each cloud deployment model has its own advantages and disadvantages, depending
on the specific needs and goals of the organization.
· Comparison: Public clouds are cost-effective but less secure. Private clouds are
more secure but expensive. Hybrid clouds offer flexibility, while multi-clouds provide
resilience.
6.3 Applications and Implications of Cloud Computing
This section explores key applications of cloud computing and discusses its implications.
6.3.1 Applications of Cloud Computing
Cloud computing has revolutionized the way businesses and individuals manage,
process, and store data. Its diverse applications span various sectors, offering scalable
and cost-effective solutions that enhance efficiency and innovation.
From hosting websites and running applications to providing data storage and
facilitating collaboration, cloud computing supports a wide array of functions that are
essential in today's digital age. By leveraging the power of the cloud, organizations can
streamline operations, reduce IT costs, and rapidly respond to changing demands. This
subsection explores the multifaceted applications of cloud computing and how they are
transforming industries and everyday life.
6.3.1.1 Data Storage
Cloud storage allows users to save data on remote servers rather than on local devices.
This makes it easier to access data from anywhere and share it with others.
Example: Services like Google Drive and Dropbox provide cloud storage solutions that
let users store and share files online. Businesses can use cloud storage to keep backups
of their data, ensuring it is safe from local hardware failures or other issues.
6.3.1.2 Web Hosting and Content Delivery
Cloud computing provides the infrastructure needed to host websites and deliver
content efficiently to users around the world.
Example: Platforms like Amazon Web Services (AWS) and Microsoft Azure offer web
156
www.OnlineMathAcademe.com
hosting services that allow businesses to run their websites on cloud servers. Content
delivery networks (CDNs) such as Cloudflare help deliver website content quickly by
caching it on servers close to the end-users.
6.3.1.3 Machine Learning and Al in the Cloud
Cloud computing offers powerful tools for developing and running machine learning
models and artificial intelligence applications.
Example: Google Cloud AI and AWS SageMaker provide cloud-based platforms for
building, training, and deploying machine learning models. These services make it easier
for data scientists and developers to create AI solutions without needing extensive local
computing resources.
6.3.2 Implications of Cloud Computing
While cloud computing offers numerous benefits, it also brings various implications that
need to be considered.
6.3.2.1 Data Security
Security is a significant concern in cloud computing. Storing sensitive data on remote
servers introduces risks such as data breaches and loss.
· Security Challenges: Cloud providers implement robust security measures, but
users must also take steps to protect their data. Issues such as data breaches,
unauthorized access, and loss of data can occur.
· Security Measures: To mitigate risks, users should use encryption, strong
authentication methods, and regularly review their security policies. Providers often
offer tools to help manage and secure data.
6.3.2.2 Scalability and Resource Management
Cloud computing allows for scalability, meaning resources can be adjusted according to
demand. However, effective resource management is essential to avoid unnecessary
costs and ensure optimal performance.
· Scalability: Cloud services can automatically scale resources up or down based on
demand, such as adding more servers during peak times and reducing them when
demand decreases.
· Resource Management: Proper management practices, such as monitoring
resource usage and optimizing performance, help control costs and ensure efficient
use of cloud resources.
6.3.2.3 Cost Considerations
While cloud computing can be cost-effective, it requires careful financial management.
Users pay for what they use, and costs can quickly add up if not monitored.
· Cost Management: To manage costs, users should regularly review their cloud
usage and spending, optimize resource allocation, and take advantage of pricing
plans that fit their needs.
157
www.OnlineMathAcademe.com
6.3.2.4 Compliance and Regulatory Issues
Organizations must ensure that their use of cloud services complies with legal and
regulatory requirements, which can vary by region and industry.
· Compliance: Organizations need to adhere to regulations related to data privacy,
security, and industry-specific standards. Cloud providers often offer tools and
features to help meet these requirements.
Class Activity
Create a list of cloud-based services you use or are familiar with. For each
service, describe how it benets you or your organization and any security
measures you use to protect your data.
www.OnlineMathAcademe.com
In simple terms, blockchain is a secure and transparent way for people to share and keep
track of information without needing to rely on one person or company to keep it safe.
6.4.1.1 Core Principles
Blockchain technology is built on several core principles that ensure its functionality and
security: Decentralization: Unlike traditional databases that are controlled by a central
authority, a blockchain is maintained by a network of computers (nodes) that work
together to validate and record transactions. This decentralized nature reduces the risk
of a single point of failure and enhances security.
· Immutability: Once a block is added to the blockchain, it cannot be altered or
deleted. This immutability ensures that the transaction history is permanent and
tamper-proof, providing a reliable and unchangeable record of all transactions.
· Consensus Mechanisms: Blockchain networks use consensus mechanisms to agree
on the validity of transactions. These mechanisms ensure that all nodes in the
network reach a unanimous decision before adding a new block to the chain.
Common consensus mechanisms include Proof of Work (PoW) and Proof of Stake
(PoS).
159
www.OnlineMathAcademe.com
6.4.1.2 Blockchain Components
Several key components make up a blockchain system:
· Node: A node is a computer that participates in the blockchain network. Each node
maintains a copy of the blockchain and helps validate transactions and blocks.
· Ledger: The ledger is a digital record of all transactions that have occurred on the
blockchain. It is distributed across all nodes, ensuring that everyone in the network
has access to the same information.
· Block: A block is a collection of transactions that are bundled together. Each block
contains a unique identifier (hash), a reference to the previous block (parent hash),
and a list of transactions.
· Transaction: A transaction is an individual entry in the blockchain. It represents the
transfer of assets or information between participants in the network.
· Blockchain Protocol: The blockchain protocol defines the rules and procedures for
how transactions are validated, how blocks are added to the chain, and how
consensus is achieved. It ensures the integrity and security of the blockchain
network.
6.4.1.3 Peer-to-Peer Network and Its Usage in Blockchain
A peer-to-peer (P2P) network is a system where computers, called nodes, communicate
and share resources directly with each other without relying on a central server. Each
node in the network can act as both a client and a server, making the network more
robust and decentralized.
For example, in a file-sharing network, users can download files directly from each
other's computers rather than from a single central server. This makes the process faster
and more efficient, as multiple users can share parts of the file simultaneously.
6.4.2 Use Cases of Blockchain Technology
Blockchain technology has a wide range of applications beyond cryptocurrency. Some
notable use cases include:
· Cryptocurrencies: Blockchain is the underlying technology for cryptocurrencies like
Bitcoin and Ethereum. It enables secure, decentralised digital transactions without
the need for intermediaries.
· Supply Chain Management: Blockchain can be used to track and verify the
movement of goods through the supply chain. This transparency helps prevent
fraud, reduce errors, and ensure the authenticity of products.
· Healthcare: In healthcare, blockchain can securely store patient records, manage
medical data, and ensure that only authorised individuals have access to sensitive
information.
· Voting Systems: Blockchain can be used to create secure and transparent voting
160
www.OnlineMathAcademe.com
systems, ensuring that votes are accurately recorded and counted, and reducing the
risk of election fraud.
www.OnlineMathAcademe.com
6.5 Applications and Implications of Blockchain
Blockchain is a special kind of technology that helps keep information safe and secure.
It's like a digital notebook that everyone can see, but no one can change. Let's explore
how it's used in the real world.
6.5.1 Tracking the Origin of Products
Blockchain technology offers a transparent and secure method to track the origin and
journey of products through various stages of the supply chain. By recording every
transaction on a decentralized ledger, blockchain ensures that each step, from the raw
material supplier to the final customer, is traceable and immutable. This traceability
helps in verifying the authenticity of products, ensuring quality, and identifying the
source of any issues that may arise.
In Figure 6.3, the connections between different entities in a supply chain are illustrated.
The blockchain records interactions between suppliers, manufacturers, fabricators,
intermediaries, retailers, and customers. Each transaction is securely logged on the
blockchain, making it possible to track the journey of a product from its origin to the end
consumer. For instance, when a supplier delivers raw materials to a manufacturer, a
record is created and added to the blockchain. This process continues at each stage, with
the fabricator, intermediary, and retailer all contributing to a transparent and verifiable
history of the product. Ultimately, the customer can access this data to confirm the
product's origin and ensure it meets the expected standards.
162
www.OnlineMathAcademe.com
Some artists use blockchain to sell digital art. Each piece of art has a
unique digital signature that proves it's the original.
163
www.OnlineMathAcademe.com
6.5.3 Data Security in Blockchain
Data security in blockchain ensures that information stored in a blockchain is protected
from unauthorized access, tampering, or loss. To explain this in simple terms, let's use an
example that relates to something we encounter daily: sending a letter through the mail.
Example: Sending a Secure Letter
Imagine you want to send a letter containing important information to a friend. You
want to make sure that no one else can read or change the letter while it's being
delivered.
· Sealing the Letter (Encryption): Before sending the letter, you place it in a special
envelope that can only be opened by your friend. This is like encryption in
blockchain, where the data is turned into a code that only the intended recipient (or
those with the right key) can understand as shown in Figure 6.5.
· Signing the Letter (Digital Signature): You then sign the envelope with your
unique signature. This signature is known to your friend, so they can be sure the
letter came from you and hasn't been altered. In blockchain, this is called a digital
signature, which ensures that the data comes from a legitimate source and hasn't
been tampered with.
www.OnlineMathAcademe.com
How It Works in Blockchain
· Encryption protects the data, so only those with permission can read it.
· Digital Signatures ensure that the data hasn't been changed and comes from a
trusted source.
· The Blockchain Network records every action, so any attempt to tamper with
the data is easily detected.
· Decentralization means the data is stored in many places, making it very hard
for hackers to attack or change the data.
By combining these techniques, blockchain provides a very secure way to store and
transfer data, making it almost impossible for unauthorized people to access or tamper
with the information.
Class Activity
Class Activity! Imagine you have a secret code. Write a message to a friend
using your code and see if they can decode it.
Do you know? Big companies like Amazon and Microsoft use their
powerful computers to help run blockchain networks.
www.OnlineMathAcademe.com
Top Tip: Edge computing is especially beneficial for applications requiring real-time
processing and low latency, such as smart cities, healthcare monitoring, and industrial
automation.
Amazing Fact: With serverless architectures, you can scale your application automatically
in response to demand, ensuring that you only use and pay for the resources you need!
www.OnlineMathAcademe.com
AI and Blockchain:
Combining AI and blockchain can enhance data security and transparency. AI
algorithms can analyze data stored on the blockchain, ensuring the data's integrity and
providing valuable insights without compromising privacy.
Example: In supply chain management, AI can predict demand and optimize logistics
based on secure and transparent data stored on the blockchain, ensuring efficient and
reliable supply chains.
loT and Blockchain:
Integrating loT with blockchain ensures secure and transparent data exchange between
loT devices. Blockchain's decentralized nature provides a tamper-proof ledger for
recording loT data, enhancing trust and security.
Example: In agriculture, loT sensors can monitor soil conditions and crop health, with
data recorded on the blockchain. This ensures the authenticity of the data, enabling
farmers to make informed decisions and improve crop yields.
Class Activity
Think about how integrating blockchain with AI or loT could benefit your
community. Discuss with your classmates and propose a project that
leverages these technologies to solve a local problem.
In conclusion, the future trends and innovations in cloud computing and
blockchain are driving significant advancements in technology. Edge
computing and serverless architectures are enhancing the efficiency and
scalability of cloud computing, while Blockchain 2.0 and the integration of
blockchain with other technologies are expanding its applications and
capabilities. These emerging trends are set to revolutionize various industries,
offering new opportunities for innovation and growth.
Summary
· Emerging technologies are new tools, systems, and methods that are currently
being developed or have just started to be used.
· AI refers to machines and software that can think and learn like humans.
· Cloud computing allows people to store and access data and applications over
the internet instead of on a local computer or server.
· Blockchain is a secure way to record and share information across many
computers, making it almost impossible to change or hack.
· loT connects everyday objects, like refrigerators, cars, and even clothes, to the
internet. This allows them to send and receive data, making our lives more
convenient.
167
www.OnlineMathAcademe.com
· AR adds digital elements to the real world using devices like smartphones or
glasses.
· VR creates a completely virtual environment that you can interact with using
special equipment.
· Quantum computers use the principles of quantum physics to process
information much faster than traditional computers.
· Biotechnology involves using living organisms, like bacteria and plants, to
create new products or solve problems.
· Virtualization is a technology that allows a single physical machine to run
multiple virtual machines.
· Scalability means you can add more resources when you need them.
· On-demand access means that you can use computing resources whenever you
need them, without waiting for a long setup process.
· laaS offers basic computing infrastructure such as servers, storage, and
networking on a pay-as- you-go basis.
· PaaS offers a complete development and deployment environment in the
cloud. It includes infrastructure (servers, storage, and networking), middleware,
development tools, and management services.
· A peer-to-peer (P2P) network is a system where computers, called nodes,
communicate and share resources directly with each other without relying on a
central server.
www.OnlineMathAcademe.com
3. In what way does a private cloud differ from a public cloud?
a) A private cloud is owned and used by multiple organizations
b) A private cloud offers less control over data and resources
c) A private cloud is dedicated to a single organization and offers more control
over data and security
d) A private cloud is cheaper and less secure than a public cloud
4. What is a key advantage of using a distributed ledger in blockchain technology?
a) Centralized control for quick decision-making
b) The ability to easily alter transaction histories
c) Enhanced transparency and security due to decentralized verification
d) Reduced computational power needed for maintaining the ledger
5. Which of the following is NOT a type of cloud service?
a) Infrastructure as a Service (laaS)
b) Platform as a Service (PaaS)
c) Software as a Service (SaaS)
d) Blockchain as a Service (BaaS)
6. Which cloud deployment model combines public and private cloud features?
a) Public Cloud
b) Hybrid Cloud
c) Community Cloud
d) Multi-Cloud
7. In the context of blockchain, what is the purpose of using a distributed ledger?
a) To allow only one central authority to manage the blockchain
b) To enable multiple participants to share and verify data in a secure and
transparent manner
c) To reduce the number of participants needed to maintain the network
d) To keep the data hidden from all participants except the central authority
8. Which type of cloud service provides a platform allowing customers to develop,
run, and manage applications without dealing with the underlying
infrastructure?
a) Infrastructure as a Service (laaS)
b) Platform as a Service (PaaS)
c) Software as a Service (SaaS)
d) Data as a Service (DaaS)
9. Which service model allows developers to build and deploy applications without
managing servers?
a) Infrastructure as a Service (laaS)
169
www.OnlineMathAcademe.com
b) Platform as a Service (PaaS)
c) Software as a Service (SaaS)
d) Serverless Architecture
10. What does Blockchain 2.0 introduce beyond basic cryptocurrency applications?
a) Enhanced mining techniques
b) Decentralized applications and smart contracts
c) Better graphics
d) Faster internet speeds
11. What is a primary advantage of serverless architectures?
a) Cost savings
b) Need for constant server management
c) Increased hardware requirements
d) Manual scaling
12. How does integrating AI with blockchain benefit data management?
a) Increases data redundancy
b) Enhances data security and transparency
c) Slows down processing
d) Increases complexity without benefits
13. Which of the following best describes immutability in blockchain?
a) The ability to modify records with administrator privileges
b) The feature that allows data to be changed only under specific conditions
c) The characteristic of data being unalterable once added to the blockchain
d) The capability to remove data from the blockchain when no longer needed
14. Which of the following is an example of edge computing in use?
a) Cloud storage services
b) Autonomous vehicles
c) Social media platforms
d) Online shopping websites
15. What is one of the environmental concerns related to blockchain technology?
a) Low energy consumption
b) High energy consumption
c) Minimal hardware use
d) Lack of data storage
16. What is the primary function of a Peer-to-Peer (P2P) network in blockchain
technology?
a) To increase the speed of transactions
b) To allow central authorities to control the network
170
www.OnlineMathAcademe.com
c) To enable direct data sharing between nodes without a central server
d) To reduce the need for encryption in the network
17. Which technology benefits from processing data at the "edge" of the network?
a) Edge computing
b) Cloud computing
c) Centralized computing
d) Distributed computing
18. What is a smart contract in the context of Blockchain 2.0?
a) A legal document
b) A self-executing contract with terms directly written into code
c) A contract managed by a third party
d) A manual agreement
Short Questions
1. Analyze the role of Peer-to-Peer Networks in Blockchain. How do they function
and why are they essential?
2. Describe the concept of immutability in blockchain. Why is it a critical feature?
3. What is edge computing and how does it benefit data processing?
4. Describe the concept of serverless architectures.
5. What are smart contracts in Blockchain 2.0?
6. How does integrating blockchain with loT improve supply chain management?
7. What advantages do serverless architectures offer to developers?
8. How does edge computing improve the efficiency of autonomous vehicles?
9. Differentiate between Elasticity and On-Demand access in cloud computing.
Long Questions
1. Explain the structure of a distributed ledger and evaluate the rationale behind its
decentralization.
2. Define cloud deployment models and assess the differences among them.
3. Classify the various types of cloud services and compare them, highlighting key
distinctions.
4. Discuss the advancements and benefits of edge computing in modern
technology.
5. Explain the concept of serverless architectures and their impact on application
development.
6. Describe Blockchain 2.0 and its advanced features.
7. How does integrating blockchain with AI and loT create new opportunities and
synergies?
8. Describe “Cloud Deployment Models” with examples.
171
www.OnlineMathAcademe.com
UNIT Legal and Ethical Aspects
7 of Computing System
Student Learning Outcomes
172
www.OnlineMathAcademe.com
Introduction
In today's digital world, computing systems play a crucial role in every aspect of our lives,
from personal devices to complex networks. As these systems become more integrated
into our daily routines, understanding the legal and ethical considerations associated
with their use is essential. This chapter delves into various aspects of digital technology,
including terms of use, privacy and security threats, and the digital divide. The legal and
ethical challenges in computing cover a range of issues such as data protection,
intellectual property rights, and compliance with relevant laws. Ethical considerations
address privacy, fairness, and the broader societal impacts of technology.
7.1 Understanding Terms of Use
“Terms of Use”, also called Terms and Conditions or Terms of Service, are legal
agreements that outline how a service or product can be used. These terms are set by the
provider (like a website, app, or software company) and must be agreed upon by the
user. The main purpose is to establish a fair and transparent relationship between the
provider and the user, ensuring that both parties understand their rights and
obligations.
Examples: When you sign up for an email service like Gmail, you are required to agree to
Google's Terms of Use. These terms explain how you can use your email account, the
types of content you are prohibited from sharing, and how Google handles your
personal data. Similarly, when we use a Pakistani online shopping platform like Daraz,
the Terms of Use may include clauses about payment methods, return policies, and
delivery procedures, ensuring that customers are aware of what to expect and what is
expected from them.
7.1.1 Importance
Understanding Terms of Use is important for several reasons:
1. Protection of Rights: Terms of Use protect users by defining their rights, such as
the right to privacy, the right to receive certain levels of service, and the right to
seek redress if things go wrong.
Example: When we use a food delivery service in Pakistan like Foodpanda, the
Terms of Use will specify what happens if your order is incorrect or if the delivery
is delayed.
2. Clarity and Transparency: These terms provide clarity and transparency about
what users can expect from a service. They explain what the service provider will
deliver, under what conditions, and what actions are not permitted. This prevents
misunderstandings and helps users make informed decisions.
Example: If we use a mobile phone for sending or receiving payments, the Terms
of Use will outline transaction limits, fees, and the process for reporting
173
www.OnlineMathAcademe.com
unauthorized transactions.
3. Legal Safeguards: For businesses, Terms of Use act as a safeguard against
misuse of their services. They set boundaries to protect the company from
potential legal issues caused by users not adhering to the rules.
Example: A Pakistani online education platform may include terms that prohibit
the sharing of course content without permission, protecting their intellectual
property.
7.1.2 Common Clauses and Conditions
Terms of Use usually contain several common clauses, which are designed to protect
both the provider and the user. These clauses include:
1. User Obligations: These clauses outline what is expected from the user.
Example: In Pakistan, popular ride-sharing apps such as Careem include terms
that require users to provide a valid phone number and prohibit the misuse of
the service for non-transportation purposes.
2. Limitations of Liability: These clauses limit the service provider's liability if
things go wrong.
Example: In Pakistan, if you use an online banking service and the app is
temporarily down, the bank's Terms of Use will typically limit their liability for
such disruptions.
3. Privacy and Data Use: Privacy clauses explain how a company will collect, use,
and protect user data. This is particularly important given the increasing
concerns around data privacy.
Example: If you use a messaging app like WhatsApp, the Terms of Use will
outline how your messages are stored and protected.
4. Intellectual Property Rights: These clauses protect the content owned by the
service provider, such as logos, software, and other proprietary materials.
Example: Pakistani news website may include terms that prohibit users from
copying and distributing their articles without permission, ensuring that their
content is not misused or misrepresented.
5. Termination of Service: This clause explains the conditions under which the
provider can terminate a user's access to the service.
Example: Social media platforms like Facebook have terms stating that they can
suspend or terminate accounts that violate community standards, such as
accounts that spread hate speech or misinformation.
7.1.3 Legal Ramifications
Violating the Terms of Use can lead to serious legal consequences. Users can be fined,
sued, or banned from using the service.
Examples: Using software without a proper license may result in legal action for
174
www.OnlineMathAcademe.com
software piracy. Companies that uses unlicensed software face legal risks and
cybersecurity threats. Another example is violating the Terms of Use of a digital payment
service like PayPak. Engaging in fraudulent activities or unauthorized transactions may
result in legal penalties, including fines or criminal charges.
7.1.4 Ethical Considerations
Ethical considerations in Terms of Use encompass fairness, transparency, and respect for
user rights. It is essential for companies to ensure that their terms are clear,
straightforward, and not overly complex or deceptive. Providers are ethically obligated
to ensure that users fully understand the terms to which they are agreeing, rather than
obscuring critical information in lengthy or confusing documents.
Example: In Pakistan, when users sign up for an online course, the terms should clearly
specify whether a certificate will be awarded, how personal data will be handled, and
whether there are any additional fees. It is ethically imperative that educational
platforms avoid misleading users into believing a course is free if there are, in fact,
hidden costs involved.
7.1.5 Personal Rights
Personal rights within Terms of Use encompass the right to privacy, the right to be
informed, and the right to withdraw consent. It is essential for users to be aware of their
rights and understand how to exercise them.
Example: Under Pakistan's Personal Data Protection Bill, users have the right to access
their data and request corrections or deletions. When engaging with services like local e-
commerce websites, users have the right to know how their personal information, such
as addresses and phone numbers, will be utilized. If a user decides to discontinue using
the platform, they have the right to delete their account and data, ensuring that their
personal information is no longer retained or used.
Class Activity
Divide students into groups and assign each group a different Terms of Use
document. Each group should highlight key clauses such as User Obligations,
Privacy and Data Use, Limitations of Liability, and Termination of Service.
Afterward, distribute a worksheet with questions asking about the main
responsibilities of users, how user data is handled, specified limitations of
liability, and conditions for service termination. Finally, have students review
and summarize the key points and important clauses of the Terms of Use from
a frequently used website or app.
175
www.OnlineMathAcademe.com
7.2 Privacy and Security Threats
In today's digital world, privacy and security threats are prevalent concerns that affect
individuals and organizations alike. These threats have the potential to compromise
personal information, financial data, and overall online security. A comprehensive
understanding of these threats is essential for safeguarding against potential risks and
ensuring the protection of sensitive information. There are some main types of privacy
and security threats.
7.2.1 Types of Security Threads
There are five primary categories of security threats of using online services.
7.2.1.1 Spam
Spam refers to unwanted messages that you receive on your email or phone.
Example: You may receive numerous text messages from unknown numbers offering
products or services that you did not ask for. In Pakistan, these messages may include
offers for fake prizes or low-cost loans. Such messages can be irritating and waste your
time. They can also attempt to trick you into providing personal information or money.
7.2.1.2 Spyware
Spyware is a type of harmful software that secretly watches what you do on your
computer or phone.
Example: If you download a free app from an unreliable source, it may install spyware on
your device. This spyware can secretly monitor your online activities, such as the
websites you visit or the information you enter, without your knowledge.
7.2.1.3 Cookies
Cookies are small files that websites place on your device when you visit them. They help
the website remember things like your login details and personal preferences.
Example: When you visit an online shopping site in Pakistan, cookies save your login
information so you do not need to enter it each time you visit. However, cookies can also
track your online activities, such as the products you view, to show you advertisements
related to your interests. This tracking helps in providing personalized ads but also
means that your browsing activities are being observed.
7.2.1.4 Phishing
Phishing is a type of scam where someone pretends to be a trustworthy organization to
trick you into giving away your personal information.
176
www.OnlineMathAcademe.com
Example: You may receive an email that looks like it comes from your bank, asking you
to click a link and enter your account details. If you follow these instructions, your money
could be at risk because the email is a fake.
Pharming
Pharming is a sophisticated technique where users are redirected to a fake website
without their knowledge.
Example: Imagine you want to access your online banking account, but due to a
pharming attack, you are sent to a counterfeit site that looks just like your bank's real
site. If you enter your login information on this fake site, the scammer collects your
details. In Pakistan, this can occur if a hacker changes the web address you type into your
browser, leading you to a fraudulent site that closely resembles the legitimate one.
7.2.2 Characteristics of Security Threats
Security threats have different features and ways of causing harm.
Spam, is often easy to recognize because it comes in large amounts and includes
unwanted advertisements. Spyware, in contrast, operates quietly in the background
and is not easily noticeable. Spam emails may have odd offers or suspicious links that
make them stand out, while spyware works silently to monitor your activities without
obvious signs.
Each type of security threat has a unique method and purpose. Spam aims to promote
products or trick you into buying something. Spyware is designed to secretly gather
your personal information. Cookies collect data on your browsing habits. Phishing
attempts to deceive you into revealing your personal details. Pharming redirects you to
fake websites to steal your information. Understanding these differences is important
for protecting yourself from each type of threat.
7.2.3 Consequences and Severity
Security threats can have serious effects. Spam is often just a nuisance, but spyware can
lead to significant privacy issues by stealing your personal data. Cookies may invade
your privacy by tracking your online activities. Phishing and pharming can cause
financial losses and give unauthorized access to your accounts. The impact of these
threats varies, but all can affect your safety and privacy. It is important to be aware of
these threats to prevent problems and keep your personal information secure.
177
www.OnlineMathAcademe.com
Over 90% of phishing attacks are carried out through email. These
scams often look like legitimate communications from trusted
organizations, making it crucial to verify the source before clicking on
any links or providing personal information.
178
www.OnlineMathAcademe.com
7.2.4.5 Guarding Against Pharming
Pharming is when attackers redirect you from a legitimate website to a fake one to steal
your information.
Example:
If you type in the URL for your bank's website, pharming can send you to a fake website
that looks just like your bank's site. To guard against pharming, always check that the
website's address is correct and secure (look for “https://" and a padlock symbol in the
address bar).
Effective online security involves using multiple strategies like spam filters, antivirus soft-
ware, and careful cookie management to cover various threat types. Combining different
security techniques provides better protection against online threats.
179
www.OnlineMathAcademe.com
3. Educational Barriers: Lack of digital literacy is another significant factor contributing
to the digital divide. Even when the technology is available, individuals may not
know how to use it effectively due to a lack of proper education and training.
4. Social Barriers: Age, gender, and disability can also affect access to technology. For
example, older adults may be less inclined or able to use new technologies, and
women in some regions may face cultural barriers that limit their access to ICT.
7.3.2 Impacts of the Digital Divide
The digital divide has far-reaching impacts on individuals and society as a whole. These
impacts can exacerbate existing inequalities and create new ones.
7.3.2.1 Educational Inequality
Access to the internet and digital tools is increasingly essential for education. Students
who lack access to these resources are at a significant disadvantage.
Example: During the COVID-19 pandemic, when schools in Pakistan and around the
world shifted to online learning, students from low-income families or rural areas
struggled to keep up with their studies due to a lack of internet access or devices. This
has led to a widening of the educational gap between different socio-economic groups.
7.3.2.2 Economic Disparities
The digital divide also has significant economic implications. In today's economy, many
jobs require at least basic digital skills. Those without access to technology or the
internet may find it challenging to secure employment, leading to higher
unemployment rates in already disadvantaged communities.
Example: In Pakistan, access to online job portals and digital banking services is often
limited to those in urban areas, further widening the economic gap between urban and
rural populations.
7.1.2.3 Social and Civic Participation
The digital divide can also affect social and civic participation. Access to social media,
online news, and digital government services allows individuals to stay informed and
engaged in civic activities. However, those without access are often excluded from these
opportunities, leading to a lack of representation and participation in democratic
processes.
Example: In Pakistan, access to e-government services is more readily available in cities,
leaving rural populations with limited means to participate in governmental processes
or access social services.
180
www.OnlineMathAcademe.com
7.2.2.4 Health Disparities
The digital divide can lead to unequal access to health information and services. Digital
platforms provide valuable resources for health education, telemedicine, and
appointment scheduling. Without access to these resources, individuals may experience
poorer health outcomes due to a lack of timely information and medical care.
Example: In Pakistan, rural communities with limited internet access may struggle to
find reliable health information online or participate in telemedicine consultations. This
can result in delays in diagnosing and treating health conditions compared to those who
have better access to digital health services.
7.2.2.5 Digital Literacy Gap
A significant digital divide also creates a gap in digital literacy. Individuals who do not
have access to technology may not develop essential digital skills, further reinforcing the
divide between those who are tech-savvy and those who are not. This gap can affect
their ability to navigate digital environments effectively and make use of online
resources.
Example: In Pakistan, people who lack access to computers and the internet may miss
out on opportunities to learn and practice digital skills. This can hinder their ability to use
online tools for everyday tasks, such as applying for jobs or accessing government
services, compared to those with regular access to digital technologies.
7.3.3 Bridging the Digital Divide
Bridging the digital divide means making sure everyone has equal access to technology
and the internet. This is important for giving everyone the same chances to learn and
grow. Here are some ways to do it:
1. Government Initiatives: The government can help by building the
infrastructure needed for internet access in areas where it's not available.
Example: In Pakistan, the Universal Service Fund (USF) works to bring internet
services to villages and remote areas where people might not have had access
before.
2. Educational Programs: Schools and community centers can teach people
how to use technology.
Example: Digital literacy programs can help students and adults learn how to
use computers and the internet for education and daily tasks.
3. Public-Private Partnerships: When the government teams up with
businesses and nonprofits, they can make technology more affordable.
181
www.OnlineMathAcademe.com
The Government of Pakistan has launched several initiatives to
increase internet access in rural areas, including the introduction of
mobile broadband services in remote regions. Despite these efforts,
many areas still lack reliable connectivity, highlighting the ongoing
challenge of bridging the digital divide.
Class Activity
Think about your own community. Are there people who may not have access
to the internet or digital devices? What can be done to help them? Write a
short paragraph on how your school or community can help bridge the digital
divide.
182
www.OnlineMathAcademe.com
Example: A research paper written by scientists who conducted the study is a primary
source. In contrast, a summary of the research written by someone else would be a
secondary source.
7.4.1.5 Critical Thinking Skills
Critical thinking skills are necessary for analyzing and evaluating information. This
means questioning the information, considering different perspectives, and making
informed decisions.
Example: If you read about a new technology, using critical thinking means looking at
various sources and viewpoints before forming an opinion.
7.4.1.6 Red Flags
Red flags are signs that indicate a source might be unreliable. These include lack of
author information, sensational headlines, or sources that do not cite their references.
Example: A website with no clear author or contact information might be unreliable.
7.4.1.7 Understanding Bias
Understanding bias involves recognizing that every source may have a certain viewpoint
or agenda. Example: A news website that only reports on one side of an issue might be
biased. It is important to consider multiple viewpoints and check if the information is
presented fairly.
www.OnlineMathAcademe.com
Moreover, computing has improved communication, making it easier and faster for
people to connect globally. Social media platforms like Facebook and X (Twitter) have
not only facilitated personal connections but also enabled social movements, such as
the #MeToo movement, to gain
global traction. In Pakistan, social media played a crucial role in raising awareness about
the 2014 Peshawar school attack, mobilizing support and solidarity.
Computing has also driven economic growth by creating new industries and job
opportunities. The rise of e-commerce platforms like Daraz has transformed traditional
business models, allowing small businesses in Pakistan to reach customers nationwide
and even internationally.
7.5.2 Negative Impacts
However, the impact of computing is not without its drawbacks. One of the major
concerns is the digital divide, where a significant portion of the population lacks access
to modern computing technologies. In Pakistan, the urban-rural divide is evident, with
rural areas having limited access to reliable internet and computing devices, leading to
unequal opportunities in education and employment. Another negative impact is the
spread of misinformation and fake news, which can lead to social unrest.
Example: During the COVID-19 pandemic, misinformation about the virus and vaccines
spread rapidly on social media, causing confusion and fear among the public. This
highlights the need for digital literacy, so people can critically evaluate the information
they encounter online.
Privacy concerns are also a significant issue, as the increased use of computing systems
has led to the collection and storage of vast amounts of personal data. Without proper
regulations, this data can be misused, leading to breaches of privacy and security. In
Pakistan, incidents like the leakage of citizens' data from the National Database and
Registration Authority (NADRA) underscore the importance of robust data protection
measures.
www.OnlineMathAcademe.com
and practices that help ensure a positive and secure online experience for everyone. By
practicing good digital citizenship, individuals can protect themselves and others from
harm, respect the rights of others, and contribute to a safe and inclusive digital
environment.
Example: In Pakistan, students should learn to communicate respectfully in online
forums and social media platforms. This means avoiding bullying or harassment and not
spreading false information. It also involves understanding the importance of digital
privacy and securing one's online accounts to prevent unauthorized access.
7.6.1 Responsible Digital Behavior
Responsible digital behavior means using technology and the internet in ways that are
respectful and safe. This includes:
1. Using Strong Passwords: Create passwords that are difficult for others to guess.
Example: Instead of using “password123", use a combination of letters,
numbers, and symbols.
2. Avoiding Phishing Scams: Do not click on suspicious links or open emails from
unknown sources that ask for personal information.
Example: If you receive an email claiming to be from a bank asking for your
account details, verify its authenticity before responding.
7.6.2 Ethical Use of Information
Ethical use of information involves handling data and content in a fair and lawful
manner.
7.6.2.1 Responsible Data Sharing
Responsible data sharing means only sharing personal or sensitive information when
absolutely necessary and ensuring that it is shared with trusted entities.
Example: When applying for a school scholarship online in Pakistan, students should
only provide personal details on secure and verified websites to prevent misuse of their
information.
7.6.2.2 Ethical Issues
Ethical issues in information use include:
1. Respecting Copyright: Do not copy or use someone else's work without permission.
Example: When writing a research paper, students in Pakistan should not copy text
from online articles without citing the source.
2. Avoiding Plagiarism: Properly attribute ideas and information to their original
authors to avoid plagiarism. This means mentioning the source of any quotes or
ideas used in assignments.
185
www.OnlineMathAcademe.com
7.6.3 Cybersecurity Awareness
Cybersecurity awareness involves understanding and implementing practices to protect
oneself from online threats.
A Cyber Crime can be reported at NR3C-FIA available at
https://www.nr3c.gov.pk
Class Activity
Try to learn how a student can become a Cyber Scout at NR3C-FIA by visiting
https://www.nr3c.gov.pk
www.OnlineMathAcademe.com
Example: Students might use spreadsheet software to analyze data for a group
project.
2. Combining Skills: Integrate human skills with machine capabilities for better
results.
Example: Using data analysis tools to interpret complex data sets while applying
human judgment to make decisions.
7.6.4.2 Teamwork and Knowledge Sharing
Teamwork and knowledge sharing involve collaborating with others and exchanging
information:
1. Group Projects: Work together on assignments or projects, each
contributing your expertise. Example: In a group project for a science class,
students should collaborate and share their research findings to complete the
assignment.
2. Sharing Insights: Exchange ideas and knowledge with peers to enhance
learning. Participate in study groups or discussions to broaden your
understanding of the subject matter.
7.6.5 Creating Accessible Digital Content
Creating accessible digital content means designing and producing content that
everyone can use, including people with disabilities.
7.6.5.1 Design for Accessibility
Designing for accessibility involves making digital content usable for all individuals,
including those with disabilities:
1. Readable Fonts: Use clear and large fonts that are easy to read.
2. Example: Choose fonts like Arial or Times New Roman and avoid overly
decorative styles.
3. Alternative Text for Images: Provide descriptions for images so that visually
impaired users can understand the content.
4. Example: Include descriptive text for charts or graphs in a report.
7.6.5.2 User Feedback
User feedback is about gathering opinions from users to improve digital content:
1. Surveys and Forms: Use surveys to collect feedback on digital content and make
necessary improvements.
Example: A er crea ng a website, ask users to provide feedback on their experience
and make adjustments based on their sugges ons.
2. Direct Communica on: Engage with users directly to understand their needs and
preferences.
Example: Ask classmates for their input on a presenta on and use their feedback to
enhance its effec veness.
187
www.OnlineMathAcademe.com
Did You Know?
In 2020, Pakistan introduced the Personal Data Protection Bill, which aims to protect
citizens' data and ensure their privacy. This bill requires organizations to obtain explicit
consent before collecting personal data and mandates the secure storage of such data.
Summary
· “Terms of Use”, also called Terms and Conditions or Terms of Service, are legal
agreements that outline how a service or product can be used.
· Violating the Terms of Use can lead to serious legal consequences. Users can be
fined, sued, or banned from using the service.
· Ethical considerations in Terms of Use encompass fairness, transparency, and
respect for user rights.
· Personal rights within Terms of Use encompass the right to privacy, the right to be
informed, and the right to withdraw consent.
· Spam refers to unwanted messages that you receive on your email or phone.
· Spyware is a type of harmful software that secretly watches what you do on your
computer or phone.
· Cookies are small files that websites place on your device when you visit them.
· Phishing is a type of scam where someone pretends to be a trustworthy organization
to trick you into giving away your personal information.
· Antivirus software protects your computer from harmful programs like spyware.
· Cookies are small files stored on your computer by websites.
· Bridging the digital divide means making sure everyone has equal access to
technology and the internet.
188
www.OnlineMathAcademe.com
3. Which of the following is a harmful software that secretly monitors your computer or
phone activities?
(a) Spam
(b) Cookies
(c) Spyware
(d) Pharming
4. Which of the following threats involves redirecting users to fake websites without
their knowledge?
(a) Phishing
(b) Spam
(c) Spyware
(d) Pharming
5. How does the digital divide affect education?
(a) It improves learning for all students
(b) It has no impact on education
(c) It creates inequality in access to digital learning resources
(d) It makes traditional teaching methods obsolete
6. What does data provenance refer to?
(a) The cost of accessing the information.
(b) The history and origins of the data.
(c) The popularity of the information source.
(d) The translation of information into multiple languages.
7. Why is understanding bias important when evaluating information?
(a) To ignore opposing viewpoints.
(b) To recognize and account for a source's viewpoint or agenda.
(c) To validate all sources as equally reliable.
(d) To avoid evaluating the information altogether.
8. Which of the following is a positive impact of computing systems on society?
(a) Increased spread of misinformation
(b) Improved accessibility to information
(c) Privacy concerns
(d) Unequal access to technology
9. What does ethical use of information involve?
(a) Copying content without permission.
(b) Respecting copyright and avoiding plagiarism.
(c) Ignoring data sources when sharing information.
(d) Using unverified information for reports.
189
www.OnlineMathAcademe.com
10. Which of the following is NOT a sign of responsible digital behavior?
(a) Using secure websites for personal data sharing.
(b) Spreading false information on social media.
(c) Respecting others' privacy online.
(d) Reporting suspicious online activities.
Short Questions
1. Why is it important for users to understand Terms of Use?
2. Differentiate between phishing and pharming.
3. Describe how cookies can be both beneficial and invasive to privacy. Give an
example of each scenario.
4. Identify two impacts of the digital divide on social and civic participation.
5. What are the key steps involved in evaluating information sources?
6. Explain how computing systems have impacted communication in society.
7. How does responsible data sharing contribute to ethical use of information?
8. Describe two ways to recognize online threats and prevent cybersecurity risks.
Long Questions
1. Explain the common clauses found in Terms of Use and describe how they protect
both the service provider and the user.
2. Explain the concept of bridging the digital divide and discuss the roles of
government initiatives in addressing this issue. Provide relevant examples from
Pakistan.
3. Explain how critical thinking skills contribute to responsible information utilization.
Provide examples of how these skills can be applied in real-life scenarios.
4. Discuss the importance of collaborative problem solving in a digital environment
and provide examples of how human-machine collaboration can enhance this
process.
5. Explain the concept of creating accessible digital content and describe strategies to
ensure digital inclusivity for individuals with disabilities.
190
www.OnlineMathAcademe.com
UNIT Online Research
8 and Digital Literacy
191
www.OnlineMathAcademe.com
Introduction
This chapter illustrates the fundamental aspects of online research and digital literacy,
which are essential for effectively navigating and utilizing the vast array of information
available on the internet. It introduces key concepts related to conducting online
research, including advanced search techniques and effective management of digital
resources. Additionally, the chapter covers the importance of formulating clear research
inquiries, understanding research ethics, and recognizing intellectual property rights.
Mastering these skills will enable students and researchers to perform rigorous and
ethical research while ensuring proper use and protection of digital content.
8.1 Introduction to Online Research and Digital Literacy
Online research is the activity of finding information on the internet about a particular
topic. It involves using various online sources, such as articles, reports, or videos, to
gather knowledge. The goal of online research is to collect correct, trustworthy, and
current information that helps in understanding a topic or solving a problem. When
conducting online research, it is essential to check if the information comes from a
reliable source. This can include official government websites, educational institutions,
or well-known newspapers. By comparing information from multiple sources, one can
ensure the accuracy of the findings.
8.1.1 Importance of Online Research
Online research is important because it allows people to access a wide range of
information quickly and easily. In today's world, where almost everything is connected
to the internet, knowing how to search for and use online information is a valuable skill.
It helps students to complete their homework, allows professionals to stay updated in
their fields, and assists everyone in making informed decisions. However, not all
information on the internet is correct. Some websites may provide false or misleading
details. It is necessary to know how to find information from reliable sources to ensure
that the facts you gather are accurate and useful.
8.1.2 Types of Online Research
Online research can be categorized into different types based on the purpose and the
kind of information needed. The most common types of online research are:
1. General Information Research: It involves finding basic information on a topic. It
is useful for gaining an overview or understanding the main points. One can use
search engines like Google to find articles, blog posts, or videos that provide
general knowledge.
2. Academic Research: This type of research focuses on finding scholarly
information for educational purposes. It involves searching for books, research
192
www.OnlineMathAcademe.com
papers, or articles from educational websites, libraries, or databases. Academic
research provides detailed and reliable information that is often written by
experts.
3. Market Research: This type is used by businesses and entrepreneurs to
understand market trends, customer behavior, and competition. Market
research helps businesses make informed decisions about launching new
products or services.
4. Fact-Checking Research: This type is used to verify if the information is accurate.
It involves checking multiple reliable sources to confirm the correctness of facts.
5. Health Research: This type involves finding information related to health issues,
medical treatments, or healthcare services. It helps people learn about
symptoms, treatments, and ways to stay healthy by using reliable health
websites and medical journals.
8.1.3 Digital Literacy
Digital literacy is the ability to use digital tools, such as computers, smartphones, and the
internet, to find, understand, create, and share information. It involves several skills,
including using search engines to look up information, assessing whether online
sources are reliable or not, and protecting personal information while using digital
platforms.
Example: If a student needs to gather information for a science project. The student uses
a search engine to find articles and videos related to the topic. Digital literacy helps the
student decide whether the sources found are trustworthy, such as checking if an article
is from a reputable source like a university or a well-known organization.
8.1.4 Key Components of Digital Literacy
Digital literacy includes several important skills that help people use technology
effectively. The key components of digital literacy are explained below.
Using Technology
Using technology involves operating devices like computers, tablets, and smartphones.
It includes knowing how to open programs, use applications, and navigate websites.
Example: If a student uses a computer to write a report for school. They need to know
how to use word processing software to type and format their report.
Searching for Information
Searching for information means using search engines to find data on the internet. This
skill includes entering relevant keywords and refining search results to locate useful
information.
Example: A farmer in Punjab wants to learn about new crop irrigation methods. They
use Google to search for terms like “modern irrigation techniques for wheat”.
193
www.OnlineMathAcademe.com
Evaluating Sources
Evaluating sources involves checking if the information you find online is reliable. This
includes looking at who created the content and whether it comes from a trustworthy
source.
Example: A teacher in Lahore finds a website claiming to have the latest educational
methods. They check if the website is run by an educational institution or a credible
organization before using its information.
Creating Digital Content
Creating digital content involves making your own materials, such as writing articles,
creating presentations, or editing photos. It requires knowledge of different software
and tools.
Example: A student in Karachi creates a PowerPoint presentation for a class project.
They use presentation software to add slides, text, and images.
Online Safety and Privacy
Online safety and privacy involve protecting personal information and staying safe on
the internet. This includes using strong passwords and recognizing potential online
threats.
Example: A person in Islamabad uses social media and sets their privacy settings to
control who can see their personal information. They also avoid clicking on suspicious
links to protect their online security.
8.1.5 Advanced Information Retrieval Techniques
Finding information online can be more effective if you use advanced techniques. These
techniques help you get better results from search engines and find exactly what you
need.
Effective Use of Search Engines
Search engines like Google are powerful tools for finding information. To use them
effectively, you need to know how to enter your search queries in a way that gives you
the best results.
Example: If a female needs information on traditional pakistani recipes. Instead of just
typing “recipes”, the student can type “traditional pakistani recipes” to get more specific
results.
Choosing Effective Keywords
Keywords are the words you type into a search engine. Choosing the right keywords
helps you find relevant information quickly. Think about the most important words
related to your topic and use them in your search.
Example: A farmer in Punjab wants to learn about “organic farming techniques”. By
194
www.OnlineMathAcademe.com
using the keywords “organic farming” instead of just “farming”, the farmer will find more
relevant information.
Using Boolean Operators ("AND", "OR", "NOT")
Boolean operators are special words that help you refine your search. They are “AND”,
“OR”, and “NOT”.
• AND is used to include multiple terms in your search.
Example: If you search for “agriculture AND irrigation”, you will get results that
include both terms.
• OR is used to find results that include either of the terms.
Example: “Crops OR vegetables”, will show results that include either word.
• NOT is used to exclude certain terms from your search.
Example: “Farming NOT pesticides” will show results about farming that do not
mention pesticides.
Advanced Search Features
Many search engines offer advanced search features that allow you to filter results by
date, location, and more. These features help you find the most relevant and recent
information.
Example: If a student in wants to find the latest news on “Pakistan's education policy”,
They can use the advanced search feature to filter results by the past year to find the
most recent articles.
Class Activity
1. Choose a topic that interests you (e.g., renewable energy, artificial
intelligence, or a historical event).
2. Use specific keywords to search for information online.
3. Find at least three sources of information and evaluate their reliability.
4. Write a short summary of what you found and include the links to your
sources.
Did you know that more than half of the world’s population uses the
internet? With so much information available, learning how to
research effectively online is a powerful tool for your education and
beyond.
www.OnlineMathAcademe.com
Class Activity
Objective: Help students practice formulating research questions and
hypotheses.
1. Choose a topic you are curious about (e.g., the impact of diet on
student energy levels, the influence of extracurricular activities on
grades, etc.).
` 2. Write a specific research question related to your topic.
3. Based on your question, develop a hypothesis that you could test
through research.
4. Share your question and hypothesis with the class and discuss how
you might design a study to answer it.
Did you know that formulating good research questions is the first
step to a successful research project? A well-thought-out question
sets the direction for your entire study and helps you focus on finding
the right answers.
Note that by learning how to ask the right questions and making
informed guesses, you can design meaningful research projects that
contribute to our understanding of the world!
196
www.OnlineMathAcademe.com
8.3.2 Effective Navigation and Managing Digital Information
When looking for information online, knowing how to search effectively is important. Start by
using specific keywords related to your topic. You can also use advanced search options to
narrow your results. Many online libraries and databases offer filters to help you search by date,
author, or subject. Once you have found useful resources, managing the information is crucial.
Save and organize digital copies of articles, take notes on key points, and keep track of your
sources for future reference. Using digital folders, note-taking apps, or reference managers helps
you stay organized and makes the research process smoother.
Example: Create a folder on your computer. Inside the folder, save PDFs of articles you find and
keep a document with important quotes or ideas.
Class Activity
1. Choose a topic for research and use an online library or open-access
repository to find at least three academic articles related to your topic.
2. Download the articles and save them in a designated folder.
3. Write a summary of each article, noting down key points and any useful
quotes.
4. Share your findings with the class, explaining how you found the articles
and how you organized your research.
Did you know that many universities around the world, including in
Pakistan, provide free access to thousands of academic journals and
research papers online? By learning how to navigate these digital
resources, you can find high-quality information for your studies
without leaving home!
Note that by effectively using digital resources and managing your
information, you can make your research process more efficient and
organized, leading to better results in your assignments and projects.
www.OnlineMathAcademe.com
rights of those involved are respected. By following ethical guidelines, researchers can avoid
causing harm, spreading misinformation, or being unfair to the people or communities they
study. Ethical research also contributes to the credibility and reliability of the results, making sure
that the research is valuable to others.
Example: If you were to falsify data or copy someone else's work without giving them credit
(plagiarism), it would be unethical. Not only could this lead to wrong conclusions, but it would
also damage your reputation as a researcher.
8.4.2 Key Principles of Research Ethics
1. Informed Consent: Always inform participants about the purpose of your
research and obtain their permission before involving them in your study.
2. Confidentiality: Keep personal information and responses of participants private
and do not share them without permission.
3. Integrity: Be honest and transparent in your research. Do not falsify data,
plagiarize, or misrepresent your findings.
4. Respect for Participants: Treat all participants with respect and ensure that your
research does not harm them in any way.
Avoiding Bias: Conduct your research in a fair and unbiased manner, and make sure your
conclusions are based on the evidence you gather.
Class Activity
1. Read a case study about a research project where ethical guidelines were
not followed (e.g., a study where participants’ privacy was not respected).
2. Discuss in groups what went wrong and how it could have been done
ethically.
3. Write down your group’s conclusions and share them with the class.
Did you know that ethical guidelines in research have been developed
over many years to protect participants and ensure that research
contributes positively to society? By following these guidelines, you
can help build trust in your work and contribute to the greater good.
Remember, being an ethical researcher means more than just
following rules—it’s about being honest, fair, and respectful in all your
research activities.
www.OnlineMathAcademe.com
8.4.1 Types of Intellectual Property
This section covers the different types of intellectual property, including patents, trademarks,
copyrights, industrial designs, and trade secrets.
Patents
A patent is an exclusive right granted for an invention, which is a product or process that provides
a new way of doing something or offers a new technical solution to a problem. A patent prevents
others from making, using, or selling the invention without the inventor's permission.
Example: A Pakistani engineer invents a new type of solar panel that is more efficient in
converting sunlight into energy. By obtaining a patent, the engineer ensures that only they can
manufacture and sell this solar panel in Pakistan for a certain number of years.
Trademarks
A trademark is a sign, logo, or name that distinguishes the goods or services of one company
from those of others. Trademarks help consumers identify the source of a product or service and
are essential for building brand recognition.
Example: The logo of National Foods is a trademark that helps customers recognize the brand
instantly when they see it on products like spices and sauces.
Copyrights
Copyright protects literary and artistic works, such as books, music, films, paintings, and software.
It gives the creator the exclusive right to use, distribute, and license their work, as well as the
ability to prevent others from copying or using it without permission.
Example: A Pakistani author writes a novel. Copyright law ensures that only the author has the
right to publish, sell, or adapt the novel into a movie.
Industrial Designs
Industrial design rights protect the visual design of objects that are not purely utilitarian. This
includes the shape, configuration, and aesthetic aspects of a product that make it unique and
appealing.
Example: A designer in Karachi creates a unique and stylish bottle shape for a new brand of
mineral water. By protecting the design, no other company can use the same bottle shape for
their products.
Trade Secrets
A trade secret is confidential information that provides a business with a competitive edge.
Unlike patents, trade secrets are not disclosed to the public. Companies protect trade secrets
through confidentiality agreements and other legal means.
Example: The recipe for a famous Pakistani soft drink, Pakola, is a trade secret. Only a few people
in the company know the exact ingredients and proportions used in making the drink.
199
www.OnlineMathAcademe.com
8.4.2 Why is Intellectual Property Important?
Intellectual property is important because it helps people protect their ideas and creations. When
someone invents something new or creates a piece of art, intellectual property laws make sure
that only they can profit from it. This protection encourages people to keep coming up with new
ideas and innovations, knowing they will be rewarded for their efforts. In short, intellectual
property supports creativity and helps drive progress by making sure that creators get the
benefits of their hard work.
Class Activity
Objective: Help students identify different types of intellectual property in
their daily lives.
1. Ask students to bring to class a product they use regularly, such as a
mobile phone, a book, or a piece of clothing.
2. Have each student identify at least one type of intellectual property
associated with their product (e.g., the brand name, the design, or the
content).
3. Discuss how intellectual property rights protect these elements and why it
is important for the creators or companies.
Did you know that Pakistan has its own Intellectual Property
Organization (IPO)? This organization is responsible for registering
and protecting intellectual property rights in the country, helping to
ensure that creators and businesses are rewarded for their innovation.
200
www.OnlineMathAcademe.com
Summary
This chapter provides a comprehensive overview of online research, digital literacy,
and intellectual property, focusing on essential skills and concepts in these areas. It
begins by highlighting the significance of online research and the various research
methods available. It then addresses digital literacy, covering key aspects such as
technology use, information retrieval, source evaluation, digital content creation, and
maintaining online safety and privacy. The chapter also explores advanced
information retrieval techniques and the formulation of research inquiries, including
research questions and hypotheses. Furthermore, it examines the use of digital
resources, research ethics, and the different types of intellectual property: patents,
trademarks, copyrights, industrial designs, and trade secrets emphasizing their
importance in protecting creative and innovative works.
201
www.OnlineMathAcademe.com
(a) It is edited by a single expert
(b) It is published in a magazine
(c) It is reviewed by other experts in the field
(d) It is freely available online
6. Which of the following is a key purpose of online libraries?
(a) Providing access to entertainment
(b) Offering a variety of academic resources
(c) Promoting social media interaction
(d) Selling digital books and materials
7. Which of the following is an essential component of ethical research?
(a) Collecting as much data as possible regardless of participants' privacy
(b) Avoiding plagiarism and providing proper credit
(c) Publishing results only if they are positive
(d) Ignoring participant consent if the research is important
8. Which principle of research ethics focuses on being truthful and transparent in
reporting findings?
(a) Confidentiality (b) Integrity
(c) Informed Consent (d) Avoiding Bias
9. Which of the following is NOT a type of intellectual property?
(a) Patents (b) Trademarks
(c) Copyrights (d) Physical Properties
10. How can a company protect a trade secret?
(a) By registering it with the IPO
(b) By applying for a trademark
(c) By keeping the information confidential and using legal agreements
(d) By publishing it in a scientific journal
Short Questions
1. How can one ensure the reliability of information found through online
research?
2. Why is it important to evaluate the reliability of online sources?
3. Explain the difference between exploratory and explanatory research questions.
4. Explain the importance of hypothesis in research process.
5. Why is it important to use specific keywords when searching for information
online?
202
www.OnlineMathAcademe.com
6. How can a researcher avoid bias in their study?
7. Describe the purpose of a trademark.
8. How does copyright differ from patent protection?
Long Questions
1. Discuss the different types of online research and their purposes, providing
examples for each type.
2. Explain the concept of digital literacy and its key components. How does it
contribute to effective use of digital tools and resources?
3. Explain the process of developing a clear and focused research question.
Illustrate your answer with examples of well-formulated and poorly-formulated
research questions.
4. Discuss the importance of research ethics in maintaining the credibility and
reliability of research findings. Explain how unethical practices could affect the
research community and society.
5. Discuss the various types of intellectual property and provide examples of each.
Explain how each type helps in protecting different kinds of creations and
innovations.
203
www.OnlineMathAcademe.com
UNIT Entrepreneurship in
9 Digital Age
Student Learning Outcomes
204
www.OnlineMathAcademe.com
Introduction
In this chapter we introduce the key aspects of entrepreneurship, focusing on the skills
and strategies necessary for business success. It covers the importance of innovation,
creativity, and problem-solving, emphasizing Design Thinking as a human-centered
approach to developing effective business solutions. The chapter guides readers
through creating a business plan, gathering market insights, and pitching ideas to
potential investors. It also touches on marketing and sales strategies, financial concepts,
and the significance of communication, collaboration, and iteration
in refining business ideas. Lastly, it highlights the role of innovation and creativity in
developing unique solutions and improving existing products and services.
9.1 Introduction to Design Thinking and Business Solutions
Let's explores how creative methods, like Design Thinking, help businesses tackle
challenges and better meet customer needs.
9.1.1 Design Thinking
Design Thinking is a method that helps us to look at problems from different angles.
Instead of just jumping to solutions, Design Thinking encourages us to first understand
the problem deeply. This method involves five key steps: Empathize, Define, Ideate,
Prototype, and Test.
· Empathize: This means putting yourself in someone else's shoes to understand
their feelings, needs, and challenges.
Example: If you are designing a new school bag, you would talk to students to
learn what they like and dislike about their current bags.
· Define: After gathering information, the next step is to clearly define the problem.
Using the school bag example, you might define the problem as: 'Students need
a lightweight, durable, and spacious bag that is comfortable to carry'.
· Ideate: Now it's time to brainstorm ideas. You can think of all possible solutions
without worrying if they are perfect. You might come up with ideas like a bag with
extra padding for comfort or one with compartments that make it easy to
organize books and supplies.
· Prototype: A prototype is a simple version of your idea that you can create
quickly. For the school bag, you might create a basic model using cardboard,
fabric, or even paper to show what it might look like.
· Test: Finally, you test your prototype to see if it works well. You could ask students
to try the bag and give feedback. Based on their comments, you can make
improvements until you have a final product that solves the problem.
9.1.2 Business Solutions
Business solutions are ways to help companies solve problems and work better.
205
www.OnlineMathAcademe.com
Example: Imagine you run a small grocery store. If you notice that items are often out of
stock, a business solution could be to order more frequently or use software to track
inventory. These steps can help keep your shelves full and customers satisfied.
Business solutions are not just about fixing problems; they also help businesses grow
and improve. For instance, if more customers start shopping online, you might offer
home delivery services to meet their needs. This way, your business can keep up with
changes and continue to thrive.
9.1.3 How Does Design Thinking Apply to Business Solutions?
In the business world, Design Thinking helps companies create products and services
that people actually want and need. For example, a company might use Design Thinking
to develop a new app that makes it easier for people to order food online. By focusing on
the user's experience and testing different ideas, they can create a solution that is both
user-friendly and successful in the market.
Class Activity
Let's apply Design Thinking to a problem in your college. Imagine that
students are having trouble finding time to do homework because they have
too many after-school activities. How could you solve this problem?
1. Empathize: Talk to your classmates to understand how they feel about
the situation.
2. Define: Write down the main problem based on what you learned
from your classmates.
3. Ideate: In groups, brainstorm different ways to help students manage
their time better.
4. Prototype: Create a simple plan or schedule that could help students
balance their activities and homework.
5. Test: Share your plan with other students and see if they think it would
work. Make any changes needed.
This activity will help you practice Design Thinking and see how it can be
used to solve everyday problems.
www.OnlineMathAcademe.com
successful, and the steps you will take to achieve your goals. It helps you think about
important details and make sure you are ready to start your business.
9.2.2 Key Parts of a Business Plan
A good business plan usually has several key parts:
· Executive Summary: This is a brief overview of your business idea. It includes
what your business does, your goals, and how you plan to achieve them. Think of
it as a summary that captures the most important points of your plan.
· Business Description: This part explains what your business is about. Describe
the products or services you will offer, your target customers, and what makes
your business unique.
Example: If you are starting a lemonade stand, explain that you will sell
refreshing lemonade to people in your neighborhood.
· Market Analysis: This section shows that you understand your market. Research
who your potential customers are, what they need, and who your competitors
are. For instance, if you are starting a pet-sitting business, find out how many pet
owners are in your area and what other pet-sitting services are available.
· Organization and Management: Describe how your business will be organized.
Include information about the team members and their roles.
Example: If you are starting a school club, explain who will be the president,
secretary, and other roles.
· Products or Services: Explain what you are selling or offering. Describe the
features and benefits of your products or services.
Example: If you are starting a tutoring service, explain how your lessons will help
students improve their grades.
· Marketing and Sales Strategy: This section details how you will attract and keep
customers. Describe your marketing methods and sales tactics. For instance, if
you are starting a crafts business, explain how you will use social media and local
fairs to sell your products.
· Financial Plan: Outline your financial goals and how you will achieve them.
Include details about your budget, funding needs, and expected revenue.
Example: If you need $100 to buy supplies for your business, explain how you
will raise this money and what you expect to earn in return.
· Business Description: "Our chai dhaba will offer freshly brewed chai using high-
quality tea leaves and a traditional recipe. Our stall will be set up near the local
bazaar.”
207
www.OnlineMathAcademe.com
· Using Digital Tools to Create a Business Plan
Creating a business plan is a critical step in launching and managing a successful
venture. In the modern world, digital tools have made this process more
accessible and efficient, ensuring that your business plan is both comprehensive
and professional. Below, we discuss the software that can help you create your
business plan and the collaborative tools that can facilitate teamwork.
9.2.2.1 Software for Business Plan Creation
There are several software solutions available that simplify the process of creating a
business plan. These tools provide structured templates, financial modeling features,
and guidance that help you develop a clear and detailed business plan.
Example: Suppose you want to start a small online bookstore. Using business plan
software like PlanGuru or Enloop, you can select a template tailored for retail businesses.
The software will guide you through creating sections like the business overview and
market analysis.
These tools often include financial calculators where you can input costs for inventory,
website development, and marketing. The software then generates financial projections,
such as estimated sales and cash flow, with visual aids like charts and graphs. This can
simplify presenting your plan to investors or applying for funding.
9.2.2.2 Collaborative Tools for Teamwork
Team collaboration is essential when developing a business plan, particularly if you are
working with partners or advisors. Collaborative tools allow multiple people to
contribute to the plan simultaneously, providing a platform for real-time feedback and
revisions.
Example: Suppose you are opening the bakery with a friend who is skilled in baking,
while you focus on the business operations. To collaborate on the business plan, you can
use tools like Google Drive or Dropbox Paper. These platforms allow both of you to work
on the same document at the same time. While your partner writes the section about the
products and recipes, you can simultaneously develop the marketing plan and financial
forecast.
These collaborative tools often feature commenting and suggestion modes, where team
members can leave feedback or propose changes without altering the original text. This
ensures that both of you can discuss ideas and make decisions together, even if you are
not physically in the same place. Additionally, version control features help you track
changes and revert to earlier drafts if necessary.
208
www.OnlineMathAcademe.com
Activity Instructions: Class Activity
1. Choose a business idea that interests you. It could be
something simple like a school bake sale or a new hobby club.
2. Write a business plan using the key parts we discussed:
· Executive Summary
· Business Description
· Market Analysis
· Organization and Management
· Products or Services
· Marketing and Sales Strategy
· Financial Plan
· Appendix (if needed)
3. Share your business plan with the class. Explain why you think your
business will be successful and how you plan to make it happen.
4. Discuss with your classmates about their plans and give constructive
feedback. This will help everyone improve their ideas and learn from
each other.
By following these steps, you'll have a solid foundation for starting your
own business and making your ideas come to life!
www.OnlineMathAcademe.com
depth conversations with potential customers to understand their preferences for
different types of bread and pastries. This type of research helps you gain insights into
what customers value most, which can inform your product offerings and marketing
messages.
Quantitative Research: Unlike qualitative research, quantitative research involves
collecting numerical data that can be measured and analyzed statistically. This type of
research is useful for identifying patterns and trends in customer behavior.
Example: Conducting a survey can help determine how often people buy coffee and
how much they are willing to pay for it. This information can then assist in setting prices
and predicting potential sales volumes.
9.3.1.2 Customer Surveys and Focus Groups
Customer Surveys: Surveys are a powerful tool for gathering information from a large
number of customers. They can be conducted online, over the phone, or in person.
Surveys usually consist of a series of questions that customers answer, providing
valuable data on their preferences, behaviors, and demographics.
Example: Before opening your bakery, you might distribute a survey to people in your
neighborhood to find out which types of baked goods they would like to see in your
shop, what times of day they are most likely to buy, and how much they are willing to
spend. This information can help you tailor your product offerings and business hours to
better meet the needs of your target market.
Focus Groups: A focus group consists of a small, diverse set of individuals brought
together to engage in detailed discussions about a product, service, or concept. The
primary objective is to obtain a comprehensive understanding of customer opinions and
attitudes.
Example: In the case of a bakery, organizing a focus group where participants sample
various breads and pastries and then discuss their preferences, likes, dislikes, and
suggestions for improvement can yield valuable qualitative data. This feedback is
instrumental in refining products and gaining deeper insights into customer needs.
9.3.2 Analyzing Market Data
After gathering market data through different research methods, the next important
step is to analyze this data. This means reviewing the information to find patterns,
trends, and insights that can help guide your business decisions. Analyzing the data
helps you understand the information and turn it into useful strategies for your business.
Understanding Trends and Patterns: When we analyze the market data, one of the key
objectives is to identify trends and patterns.
Example: If you conduct a survey to determine how often customers purchase bakery
products, the data will likely show that most purchases occur on weekends. This pattern
suggests that focusing
210
www.OnlineMathAcademe.com
your marketing efforts or offering special promotions on weekends can effectively
increase sales.
211
www.OnlineMathAcademe.com
neighborhood. A business pitch would include:
• What the idea is: A juice shop that sells fresh, healthy, and affordable juices.
• Who the customers are: People in your neighborhood, especially those who
care about their health.
• Why it will work: There are no other juice shops nearby, and people are
becoming more health-conscious.
Some of the most famous companies in the world, like Apple and
Google, started with simple business pitches. The founders had to
explain their ideas clearly to get support and investment!
www.OnlineMathAcademe.com
• Target Audience: “Our target customers are local shop owners and
restaurant managers who want to reach more customers by having an online
presence”.
9.3.5 Importance of Pitching
Being able to pitch your idea is important because it helps you get the support you need
to turn your idea into reality. Whether you're starting a small business or launching a big
project, a good pitch can make all the difference.
9.4 Developing Effective Marketing and Sales Strategies
Marketing and sales are essential components of any successful business. They help
businesses attract customers, increase sales, and grow their brand. In this section, we will
explore how to develop effective marketing and sales strategies, using examples from
the Pakistani context.
9.4.1 Understanding Your Market
Before marketing a product or service, it is essential to understand the market. This
involves identifying potential customers, their needs, and how your product can address
those needs.
Example: If you are selling traditional Pakistani clothing, your target market includes
individuals preparing for Eid or weddings, as these events typically require traditional
attire.
9.4.2 Creating a Marketing Plan
A marketing plan details the strategies for reaching your target market. It includes
selecting promotional channels, such as social media, television, or word-of-mouth.
Example: When launching a new brand of Pakistani spices, advertising on cooking
shows or collaborating with social media influencers who focus on traditional Pakistani
cuisine would be effective.
9.4.3 Sales Strategies
Sales strategies are tactics used to convince customers to purchase your product. This
might include offering discounts, running promotions, or providing excellent customer
service.
Example: During Ramadan, many grocery stores in Pakistan offer special deals on food
items, which encourages more people to buy in bulk.
213
www.OnlineMathAcademe.com
Class Activity
Imagine you are starting your own business selling a product of your
choice. Develop a marketing and sales strategy for your business. Consider
your target market, how you will reach them, and what sales tactics you will
use. Share your plan with the class.
In Pakistan, the e-commerce sector is rapidly growing, with more people shopping online
than ever before. Businesses that effectively market their products online can reach a
much wider audience.
214
www.OnlineMathAcademe.com
the shop are Rs. 30,000, the profit would be:
Profit = Revenue — Costs = 50,000 — 30,000 = Rs. 20,000
www.OnlineMathAcademe.com
9.5.3 Loans and Interest
Sometimes, businesses need more money than they currently have, so they take out a
loan from a bank or another financial institution. A loan is borrowed money that must be
paid back with interest. Interest is the cost of borrowing money, usually expressed as a
percentage of the loan amount.
Example: if a tea shop in Multan takes a loan of Rs. 100,000 at an interest rate of 10% per
year, they will have to pay back Rs. 110,000 after one year:
Total Repayment = Loan Amount + Interest = 100,000+ 10% x 100,000 = Rs. 110,000
Class Activity
Calculate the total amount to be repaid on a loan of Rs. 50,000 over one year at
an interest rate of 8%. Analyze how the interest rate impacts the total
repayment amount.
www.OnlineMathAcademe.com
storytelling can enhance your argument by making it more engaging and persuasive.
Example: If the debate topic is “Should plastic bags be banned?” telling a story about a
visit to the beach where you observed the negative impact of plastic waste on marine life
can make your argument more relatable and convincing.
Think of this phase like designDid you know that one of the most powerful speeches in
history, the I Have a Dream speech by Martin Luther King Jr., is remembered not just for its
message but for the way it was delivered? The combination of storytelling, emotion, and
clear communication made it unforgettable.ing a new house. You need blueprints to show
where the rooms and furniture will go before you start building.
217
www.OnlineMathAcademe.com
9.7 Collaboration and Iteration
9.7.1 Collaboration
Collaboration is when two or more people work together to achieve a common goal. It
involves sharing ideas, resources, and efforts to solve problems or create something
new. In Pakistan, collaboration can be seen in many areas, such as when students work
together on a group project, or when community members come together to organize
an event.
Class Activity
Imagine you and your classmates have been asked to create a science model
for an exhibition. Instead of each of you working separately, you decide to
collaborate. One student might be good at drawing diagrams, another at
building models, and someone else at explaining the project to others. By
collaborating, you combine your strengths and produce a better project than
any one of you could have done alone.
9.7.2 Iteration
Iteration means repeating a process with the aim of getting closer to a desired result. It
involves making changes and improvements based on feedback until the final outcome
is achieved. In everyday life, iteration can be seen in activities like cooking, where you
might adjust the ingredients and taste as you go until the dish is perfect.
Example: Suppose your class is designing a new logo for a school event. You begin with
an initial design and share it with your classmates for their opinions. Based on their
feedback, you revise the design, adjusting colors and shapes. You then seek more
feedback and make further changes. This cycle of designing, gathering feedback, and
refining continues until you have a final logo that everyone approves. This process
illustrates iteration.
Class Activity
Form groups of 4-5 students. Each group will create a simple poster on a topic
of your choice. After the first draft, exchange posters with another group for
feedback. Use their suggestions to improve your poster, then share the
updated version with the class.
www.OnlineMathAcademe.com
The famous Indus Valley Civilization, which existed in what is now Pakistan, showed early
examples of collaboration and iteration in their town planning and construction
techniques!
www.OnlineMathAcademe.com
• Think Outside the Box: Look at problems from different perspectives.
Sometimes the best solutions are the ones that nobody else has thought of.
• Collaborate: Working with others can spark new ideas and lead to
innovative solutions.
Class Activity
Think of a problem in your college or community that needs a solution. In
groups, brainstorm creative ways to solve the problem. Present your ideas to
the class!
Summary
This chapter provides a comprehensive overview of essential entrepreneurship concepts
and skills. It begins by introducing entrepreneurship and the importance of innovation,
problem-solving, and value creation. The chapter explores Design Thinking, a method
for developing human centered solutions, and details how to create a business plan,
including market analysis and financial forecasting. It also covers gathering market
insights, pitching ideas, and implementing marketing and sales strategies. Financial
management, effective communication, and collaboration are discussed as key
components for business success. Finally, the chapter encourages innovation and
creativity, equipping students with the tools needed to start and sustain their own
ventures.
www.OnlineMathAcademe.com
3. What is the first step in creating a business plan?
a) Financial forecasting
b) Market analysis
c) Defining the business idea
d) Setting sales targets
4. Which technique is commonly used in Design Thinking?
a) SWOT Analysis
b) Brainstorming
c) Lean manufacturing
d) Data mining
5. What is the purpose of collecting market insights?
a) To set product prices
b) To understand customer needs and market trends
c) To calculate taxes
d) To manage inventory
6. A successful business pitch should be:
a) Long and detailed
b) Clear and persuasive
c) Focused on personal achievements
d) Directed only at investors
7. What is a key component of effective marketing?
a) High pricing
b) Strong brand identity
c) Random advertising
d) Reducing production costs
8. Financial concepts for business help entrepreneurs to:
a) Avoid paying taxes
b) Manage resources and plan for growth
c) Increase spending
d) Compete with larger companies
9. Which skill is crucial for storytelling in business?
a) Technical expertise
b) Emotional connection
c) Physical strength
d) High financial investment
10. Innovation in business is primarily about:
a) Inventing new technologies
221
www.OnlineMathAcademe.com
b) Improving existing products and processes
c) Reducing operational costs
d) Increasing production speed
Short Questions
1. Define entrepreneurship in your own words.
2. What is the main focus of Design Thinking?
3. List the key steps involved in creating a business plan.
4. Why is market research important for a new business?
5. Explain the importance of a business pitch.
6. How can storytelling benefit a business?
7. Describe one financial concept that is important for business.
8. Why is collaboration important in the entrepreneurial process?
Long Questions
1. Discuss the importance of Design Thinking in developing business solutions.
Provide examples of how it can be applied.
2. Explain the process of creating a business plan, and why each step is critical to the
success of a new business.
3. How does market insight influence business decisions? Give examples of how
businesses can use this information.
4. Describe the key elements of an effective business pitch and how to prepare one.
5. What are the essential components of a marketing and sales strategy? Discuss
how these strategies can be tailored for different markets.
6. Explain the significance of financial management in a business. How do financial
concepts such as budgeting and cash flow affect business operations?
7. Discuss the role of communication and storytelling in building a brand and
connecting with customers.
8. How do collaboration and iteration contribute to the success of an
entrepreneurial venture? Provide examples of how these processes work in
practice.
222
www.OnlineMathAcademe.com
223
www.OnlineMathAcademe.com