0% found this document useful (0 votes)
22 views54 pages

Algorithmic Thinking With Python Module 1 Class Note

Uploaded by

Nayana.A.R Nair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views54 pages

Algorithmic Thinking With Python Module 1 Class Note

Uploaded by

Nayana.A.R Nair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

ALGORITHMIC THINKING WITH PYTHON

Class Note Module – 1


1.1 PROBLEM-SOLVING STRATEGIES - Problem-solving strategies defined - Importance of
Understanding Mul ple Problem-solving Strategies - Trial and Error - Algorithm and Heuris c - Means-
Ends Analysis

1.2 THE PROBLEM-SOLVING PROCESS - Computer as a model of computa on - Understanding the


Problem - Formula ng a Model - Developing an Algorithm - Wri ng the Program - Tes ng the Program -
Evalua ng the Solu on

1.3 ESSENTIALS OF PYTHON PROGRAMMING - Crea ng and using Variables in Python, Numeric
types in Python, Using strings in Python, Using the math module, Using the Python Standard Library for
handling file I/O, basic mathema cs, etc Using the NumPy library

1.1.1 Problem-solving strategies

Problem-solving in the field of engineering, science and technology involves iden fying, analyzing, and
finding solu ons to complex issues using a systema c approach. It requires cri cal thinking, crea vity,
and technical knowledge.

Example: Imagine a scenario where the stability of a bridge has to improve. The step-by-step approach
for a solu on is,

Algorithm Thinking with Python – Module1 Prepared by:


1|Page Harish Kumar B, APME, CET
a. Define the Problem: Clearly state the issue. For instance, “Enhance the bridge to withstand
higher wind loads and improve safety.”
b. Gather Informa on: Collect relevant data, such as current wind loads and exis ng bridge
designs.
c. Brainstorm Ideas: Generate mul ple solu ons, like reinforcing support pillars or using advanced
materials.
d. Evaluate and Select the Best Solu on: Assess each idea based on feasibility, cost, and impact,
then choose the best one.
e. Plan and Design: Develop detailed plans and designs, including blueprints and material
calcula ons.
f. Test and Prototype: Create a small-scale model and test it under various condi ons.
g. Implement the Solu on: Execute the plan, making adjustments as needed.

1.1.2 Importance of Understanding Mul ple Problem-Solving Strategies

Understanding mul ple problem-solving strategies is crucial for several reasons. Mastering mul ple
problem-solving strategies equips individuals with a versa le toolkit to tackle challenges effec vely in
various personal, academic, and professional contexts. The advantages of mul ple approaches in solving
problems are illustrated in the below table.

No Aspect Importance
Flexibility and Allows choosing the most effective method for each
1
Adaptability unique problem.

Enhanced Critical
2 Encourages analyzing problems from different angles.
Thinking

Improved
3 Helps quickly identify the most efficient solution.
Efficiency

Increased Boosts confidence by providing multiple tools to


4
Confidence tackle challenges.

Encourages Promotes thinking outside the box and innovative


5
Creativity solutions.

Better
6 Enhances teamwork by sharing different approaches.
Collaboration

Ensures persistence by having alternative methods


7 Resilience
when one strategy fails.

1.1.3 Mul ple Problem-solving Strategies

Mul ple problem-solving strategies provide a diverse toolkit that enhances flexibility, crea vity, and
efficiency. By understanding and applying different approaches—such as trial and error, algorithms,
heuris cs, and Means-Ends Analysis etc., individuals can tackle challenges more effec vely, adapt to

Algorithm Thinking with Python – Module1 Prepared by:


2|Page Harish Kumar B, APME, CET
new situa ons, and innovate solu ons. Mastering these strategies not only improves cri cal thinking
and decision-making but also fosters resilience and collabora on, empowering individuals to address
complex issues with confidence and insight.

1.1.4 Trial and Error Method

The Trial and Error method is a fundamental problem-solving technique that involves tes ng various
solu ons un l the correct one is found. It is widely used in fields such as Engineering, science, and
computer programming.

Algorithm Thinking with Python – Module1 Prepared by:


3|Page Harish Kumar B, APME, CET
1.1.4.1 Process of trial and error method

 Iden fica on of the Problem: Clearly define the problem to solve.


 Generate Possible Solu ons: Come up with various poten al solu ons or ac ons to take.
 Test Solu ons: Implement one solu on at a me.
 Evaluate Results: Assess whether the solu on worked.
 Iterate: If the solu on didn't work, learn from the failure, discard the ineffec ve solu on, and
try the next op on. Repeat this process un l a successful solu on is found.

1.1.4.2 Advantage/Disadvantage of trial and error method

Advantages Disadvantages

Encourages Creativity: Promotes innovative Time-Consuming: Can take a long time to find
thinking and problem-solving skills. the correct solution.

Hands-On Learning: Provides practical Resource-Intensive: May require significant


experience and learning from mistakes. resources and effort.

Adaptability: Flexible approach that can be Inefficiency: Not always the most efficient
applied to various problems. method, especially for complex problems.

Immediate Feedback: Offers quick feedback on Frustration: Can lead to frustration if solutions
what works and what doesn’t. are not quickly found.

Resilience Building: Helps build perseverance Risk of Repetition: May lead to repeating the
and resilience through repeated attempts. same mistakes without progress.

1.1.4.3 Applica on and Suitable Scenarios

 Simple Everyday Tasks: For example, finding the right key for a lock. You try each key un l one
fits and opens the lock.
 Learning New Skills: When learning to ride a bike, a person may fall mul ple mes but learns
from each fall un l they can balance and ride successfully.
 Scien fic Research: In laboratories, scien sts o en use trial and error to test different
hypotheses or to determine the right condi ons for an experiment.
 Limited Op ons: When the number of possible solu ons is rela vely small.
 Low Stakes: When the cost of failure is low, making repeated a empts feasible.
 Immediate Feedback: When each trial quickly shows whether it is a success or failure

Here are a few math ques ons that can be a empted using the trial and error method:

Algorithm Thinking with Python – Module1 Prepared by:


4|Page Harish Kumar B, APME, CET
 Es mate the square root of 725.
 Find a real root of the equa on x3 - 7x2 + 14x - 8 = 0
 Determine the integer solu ons for 2x + 3y = 17
 Find the integer roots of the polynomial x4 - 10x3 + 35x2 - 50x + 24 = 0

1.1.5 Algorithm and Heuris c

Two fundamental approaches to problem-solving are algorithms and heuris cs. Algorithms provide a
step-by-step procedure that guarantees a solu on, making them ideal for problems with clear rules and
structure. Heuris cs, on the other hand, are prac cal shortcuts or rules of thumb that offer solu ons
more quickly when an exact method is imprac cal. Understanding both approaches allows engineers to
tackle a wide range of problems effec vely.

1.1.5.1 Algorithms

An algorithm is a step-by-step procedure or formula for solving a problem. It is a precise, well-defined


sequence of instruc ons that guarantees a solu on if followed correctly.

Algorithms are used in scenarios requiring precise and op mal solu ons, such as data processing,
network rou ng, and automated control systems.

Main Characteris cs of Algorithm:

 Determinis c: Produces the same output for a given input every me.
 Complete: Ensures a solu on is found if one exists.
 Op mal: Finds the best possible solu on.

Examples of effec ve Algorithms:

 Sor ng Algorithms: QuickSort, MergeSort.


 Search Algorithms: Binary Search, Depth-First Search (DFS).

1.1.5.2 Heuris cs

A heuris c is a problem-solving approach that employs a prac cal method or various shortcuts to
produce solu ons that may not be op mal but are sufficient for reaching an immediate goal. They use
rules of thumb that offer solu ons more quickly when an exact method is imprac cal.

Heuris cs are applied in complex, real-world problems where quick, feasible solu ons are needed, such
as AI pathfinding, op miza on problems, and decision-making processes.

Main Characteris cs of Heuris cs:

 Non-determinis c: May produce different outputs for the same input.


 Incomplete: Does not guarantee a solu on.
 Approximate: Provides a good enough solu on quickly.

Examples for Heuris cs solu on for solving typical problems:

 Traveling Salesperson Problem (TSP): Using nearest neighbor heuris c.


 An virus So ware: Heuris c-based detec on of malware.

Algorithm Thinking with Python – Module1 Prepared by:


5|Page Harish Kumar B, APME, CET
1.1.5.3 Comparison of Algorithm and Heuris cs

Aspect Algorithm Heuristic


Step-by-step procedure for solving Practical method for quick,
Definition
a problem approximate solutions

Determinism Deterministic Non-deterministic

Completeness Complete Incomplete

Optimality Optimal Approximate

Nearest Neighbor for TSP,


Examples QuickSort, Binary Search
Heuristic-based Antivirus

1.1.6 Means-Ends Analysis (MEA)

Means-Ends Analysis (MEA) is a problem-solving technique used to reduce the difference between the
current state and the desired goal state by breaking down the problem into smaller, manageable sub-
problems. It is a powerful problem-solving tool that helps engineers systema cally reduce the gap
between the current state and the desired goal by focusing on achievable sub-goals. This method
enhances problem-solving efficiency and effec veness, making it a valuable technique in engineering
prac ce.

Key Terminologies and Concepts in MEA

 Current State: The ini al condi on or star ng point of the problem.


 Goal State: The desired outcome or solu on to the problem.
 Operators: Ac ons or steps that can be taken to move from the current state to the
goal state.
 Subgoals: Intermediate steps or milestones that help bridge the gap between the
current state and the goal state.

Important Steps in MEA

 Iden fy the Goal: Clearly define the end goal or desired outcome.
 Evaluate the Current State: Assess the current situa on and iden fy the differences
between the current state and the goal state.
 Determine the Means: Iden fy the operators or ac ons that can reduce the differences.
 Set Subgoals: Break down the problem into smaller subgoals that can be achieved
sequen ally.

Algorithm Thinking with Python – Module1 Prepared by:


6|Page Harish Kumar B, APME, CET
 Apply Operators: Implement the ac ons to achieve each subgoal, progressively moving
closer to the goal state.

Typical Examples where MEA is effec vely u lized for solu ons

i) Robot Naviga on:


(a) Goal: Move a robot from point A to point B.
(b) Current State: Robot is at point A.
(c) Subgoals: Navigate through intermediate points (C, D, E) to reach point B.
(d) Operators: Move forward, turn le , turn right.
ii) So ware Development:
(a) Goal: Develop a new so ware feature.
(b) Current State: Feature is not implemented.
(c) Subgoals: Design the feature, write the code, test the feature, deploy the feature.
(d) Operators: Coding, debugging, tes ng, deploying.
iii) Travel Planning:
(a) Goal: Plan a trip from New York to Paris.
(b) Current State: Currently in New York.
(c) Subgoals: Book a flight, arrange accommoda on, plan i nerary.
(d) Operators: Search for flights, make reserva ons, create a travel schedule.

Algorithm Thinking with Python – Module1 Prepared by:


7|Page Harish Kumar B, APME, CET
1.2.1 Computer as a model of computa on

The Model of Computa on is a theore cal framework helps analyze and design computa onal systems,
algorithms, and so ware. Various models, such as the Random Access Machine (RAM), Turing Machine,
Combinatory Logic, and Finite State Machine (FSM), provide different perspec ves and tools for
understanding computa onal processes. By studying these models, engineers can gain deeper insights
into the capabili es and limita ons of computa onal devices.

A) Random Access Machine (RAM)

A RAM is a theore cal model of computa on that mimics the architecture of real-world
computers with random access memory. It operates similarly to the von Neumann
architecture but focuses on abstract opera ons. The RAM model is used to analyze the
me complexity of algorithms by coun ng the number of basic opera ons performed.

The main Components are

 Memory - A large array of cells that can be accessed randomly.


 CPU - Performs arithme c and logical opera ons.
 Instruc on Set - A set of opera ons like read, write, add, and compare.
 Input/output units

B) Turing machine- A Turing machine is an abstract mathema cal model that defines a
hypothe cal machine capable of performing computa ons by reading and wri ng symbols
on an infinite tape according to a set of rules.

Algorithm Thinking with Python – Module1 Prepared by:


8|Page Harish Kumar B, APME, CET
C) Combinatory logic- Combinatory logic is a nota on to eliminate the need for variables in
mathema cal logic. It is used as a founda on for func onal programming languages and
can represent computa on through the combina on of func ons.

D) Finite State Machine- A FSM is a computa onal model consis ng of a finite number of
states, transi ons between these states, and ac ons. It is used to design both computer
programs and sequen al logic circuits.

How does a computer serve as a model of computa on?

A computer serves as a model of computation by providing a framework that


represents how a problem can be solved through structured processing of inputs to
produce outputs using a series of well-defined steps called algorithms. This model
abstracts the essential capabilities of computation — such as storing information,
performing operations on data, and following instructions — enabling programmers
and researchers to design, analyze, and implement solutions efficiently.

Key points:

 The computer processes data by executing a set of instructions (program) in a


stepwise manner, reflecting the logic of the problem-solving method.
 Abstract computational models, such as the Turing machine or Random Access
Machine, help understand the fundamental limits and possibilities of computation
beyond specific hardware.
 The computer uses machine code (binary instructions) that the CPU executes
directly to carry out operations, making it a concrete realization of computation
theories.
 This model allows studying the efficiency, correctness, and feasibility of algorithms
independently of the hardware specifics, guiding algorithm design and optimization.

In essence, a computer models computation by transforming inputs through a


rigorous, rule-based process to achieve outputs, serving as both a tangible and
theoretical tool for solving problems systematically.

What core components map a real computer to an abstract model of computa on?

The core components that map a real computer to an abstract model of


computation include:

1. Memory: Represents storage for data and instructions. In an abstract machine,


memory holds variables, the program, and intermediate values just like RAM in a
real computer.
2. Processor (Control Unit and ALU): The processing unit executes instructions step-
by-step. The control unit directs the sequence of execution while the Arithmetic

Algorithm Thinking with Python – Module1 Prepared by:


9|Page Harish Kumar B, APME, CET
Logic Unit (ALU) performs calculations and logical operations. This maps to the CPU
in a real computer.
3. Input and Output Mechanisms: Abstract machines define inputs entering the
system and outputs produced, similar to keyboards, sensors, monitors, and printers
on a real computer.
4. Registers and Stack: Abstract models include registers to hold small pieces of data
temporarily and a stack for function calls and managing intermediate computation,
analogous to hardware registers and stack memory.
5. Instruction Set and Execution Cycle: The abstract machine has a defined set of
operations (instructions) it can perform, and a control flow that interprets and
executes these instructions in sequence, just like the instruction set architecture and
fetch-decode-execute cycle of a real CPU.
6. Interpreter or Execution Engine: The component in the abstract machine that
processes instructions, manages memory, and controls data movements
corresponds to the machine language interpretation or microcode in real
computers.

By abstracting these components, the model focuses on the logical flow of


computation—how data is transformed step-by-step—without detailed hardware
specifics, thereby bridging theoretical algorithms and practical computing.

1.2.2 Steps in Problem Solving

1. Understanding the Problem

The first step in problem-solving is to thoroughly understand the problem. This involves
iden fying the problem's requirements, constraints, and objec ves. Engineers must ask
ques ons to clarify any ambigui es and gather all necessary informa on. Understanding the
problem also involves recognizing what the problem is not, which helps in avoiding unnecessary
work. A clear understanding of the problem ensures that subsequent efforts are focused and
effec ve.

2. Formula ng a Model

Once the problem is understood, the next step is to formulate a model. This involves crea ng a
simplified representa on of the problem that captures its essen al aspects. The model can be
mathema cal, logical, or graphical, depending on the nature of the problem. Formula ng a
model helps in visualizing the problem, understanding its structure, and iden fying
rela onships between different elements. A well-defined model is crucial for developing an
effec ve solu on.

3. Developing an Algorithm

With a model in place, the next step is to develop an algorithm. An algorithm is a step-by-step
procedure for solving the problem. It should be clear, unambiguous, and finite. Developing an
algorithm involves breaking down the problem into smaller, manageable parts and defining the

Algorithm Thinking with Python – Module1 Prepared by:


10 | P a g e Harish Kumar B, APME, CET
sequence of opera ons required to solve each part. The algorithm should be designed to be as
efficient as possible, minimizing computa onal resources and me.

4. Wri ng the Program

A er developing an algorithm, the next step is to translate it into a programming language.


Wri ng the program involves coding the algorithm using appropriate syntax and programming
constructs. It requires a good understanding of the chosen programming language and
a en on to detail to ensure that the code accurately implements the algorithm. The program
should be well-documented, with comments explaining the purpose of each sec on of code,
making it easier to understand and maintain.

5. Tes ng the Program

Once the program is wri en, it needs to be tested to ensure it works correctly. Tes ng involves
running the program with different input values and verifying that it produces the expected
output. This step helps iden fy any errors or bugs in the code. Tes ng should be thorough,
covering all possible scenarios, including edge cases and unexpected inputs. Debugging is o en
a part of this process, where iden fied issues are resolved to improve the program's reliability
and accuracy.

6. Evalua ng the Solu on

The final step is to evaluate the solu on. This involves assessing the program's performance,
efficiency, and correctness. The solu on should be evaluated against the original problem
requirements to ensure it meets all objec ves and constraints. Addi onally, the solu on's
scalability and maintainability should be considered, especially for long-term use. Evalua on
may also involve ge ng feedback from users or stakeholders and making necessary
adjustments to improve the solu on. This step ensures that the problem-solving process
delivers a prac cal, effec ve, and op mized solu on.

Algorithm Thinking with Python – Module1 Prepared by:


11 | P a g e Harish Kumar B, APME, CET
1.3.0 Python Interpreter, Installa on and Coding Environment

1.3.0.1 Short History of Python

 1980s: Crea on of Python - Python was conceived in the late 1980s by Guido van Rossum at the
Centrum Wiskunde & Informa ca (CWI) in the Netherlands. Van Rossum wanted to create a
successor to the ABC language, which was designed for teaching programming but had
limita ons.
 1991: First Release - Python was first released in February 1991. It was designed with an
emphasis on code readability and simplicity, borrowing features from other languages like C,
Modula-3, and ABC.
 2000: Python 2.0 - Python 2.0 was released in October 2000, introducing significant features like
list comprehensions and garbage collec on through reference coun ng. Python 2 remained
widely used un l the introduc on of Python 3.
 2008: Python 3.0 - Python 3.0 was released in December 2008 to address the fundamental
design flaws of Python 2.x and improve the language. However, Python 3 was not backward
compa ble with Python 2, leading to a lengthy transi on period.
 2020: End of Python 2 - Python 2 reached its end of life on January 1, 2020, marking the official
transi on to Python 3.

1.3.0.2 How Python Interpreter works?

Algorithm Thinking with Python – Module1 Prepared by:


12 | P a g e Harish Kumar B, APME, CET
1. Lexical Analysis - The interpreter reads the code and breaks it into tokens: x = 10, y = 20, print,
(, x, +, y, ).
2. Parsing - The parser checks that this sequence of tokens follows Python’s syntax rules and
constructs an AST represen ng the assignment opera ons and the func on call.
3. Bytecode Compila on - The AST is then compiled into bytecode instruc ons that the Python
Virtual Machine can execute.
4. Execu on - The PVM interprets the bytecode, assigning values to x and y, and then calls the print
func on with the result of x + y (which is 30).
5. Output - The result 30 is displayed on the screen.

The Python interpreter works through several stages: it reads and tokenizes the source code, parses it
into an abstract syntax tree, compiles it into bytecode, and then executes this bytecode using the Python
Virtual Machine. This process allows Python to efficiently run your code, while also managing memory
and handling errors automa cally.

1.3.0.3 Why Python Is So Popular

1. Ease of Learning and Use - Python’s simple and readable syntax makes it an ideal language for
both beginners and experienced programmers. The ease of wri ng and understanding code
reduces the learning curve, which has contributed to its widespread adop on.
2. Extensive Libraries and Frameworks - Python boasts a rich ecosystem of libraries and
frameworks that make data analysis, machine learning (ML), and ar ficial intelligence (AI), Web
development, GUI applica ons more accessible. Some of the most popular libraries include,
a. Web Development - Django, Flask, FastAPI, Pyramid, Bo le
b. Data Science and Analysis - Pandas, NumPy, SciPy, Matplotlib, Seaborn
c. Machine Learning and AI - Scikit-learn, TensorFlow, PyTorch, Keras, XGBoost
d. Natural Language Processing (NLP) - NLTK, spaCy, Gensim, TextBlob, Hugging Face
Transformers, Olema
e. Web Scraping - Beau fulSoup, Scrapy, Requests, Selenium
f. Automa on and Scrip ng - Selenium, Requests, PyAutoGUI, OpenPyXL
g. Data Visualiza on - Plotly, Bokeh, Altair, Dash
h. GUI Development - Tkinter, PyQt, Kivy, wxPython, PyGTK
i. Deep Learning - TensorFlow, PyTorch, Keras, Theano
j. Game Development - Pygame, Panda3D, Arcade, Pyglet
3. Community Support - Python has a large and ac ve community, which means abundant
resources, tutorials, and documenta on are available. The community con nuously contributes
to the development of new libraries and tools, ensuring that Python stays at the forefront of
technology.
4. Interoperability - Python can easily integrate with other programming languages and tools,
making it versa le for different environments. For example, it can be combined with C/C++ for
performance-cri cal tasks or used alongside R for sta s cal analysis.
5. Pla orm Independence - Python is cross-pla orm, meaning it can run on various opera ng
systems, including Windows, macOS, and Linux. This flexibility makes it suitable for diverse
development environments.
6. Strong Support for Data Science Tools - Python is the language of choice for many data science
tools like Jupyter Notebooks and Anaconda, which streamline the process of data analysis and
machine learning.
7. Emphasis on Rapid Prototyping- Python’s ability to allow quick prototyping and itera ve tes ng
is invaluable in fields like ML and AI, where experimenta on is crucial.

Algorithm Thinking with Python – Module1 Prepared by:


13 | P a g e Harish Kumar B, APME, CET
8. Industry Adop on - Python’s adop on by major companies and organiza ons (such as Google,
Facebook, and NASA) for their AI and data science ini a ves has solidified its posi on as a
leading language in these domains.

1.3.0.4 Installing Python

 Downloading Python - Official Website: Go to the official Python website and navigate to the
download sec on.
 Choose Version - Select the version of Python you want to install. The latest stable version is
recommended for most users.

1.3.0.5 Popular Python Coding Environments

Python can be installed on various opera ng systems via a straigh orward process, and there are
numerous coding environments available for different needs. Whether you’re a beginner or an
advanced developer, there's a suitable environment for you, ranging from simple text editors to
powerful IDEs and interac ve notebooks.

1. Integrated Development Environments (IDEs) - PyCharm, VS Code (Visual Studio Code), Spyder,
Thonny
2. Text Editors - Sublime Text, Atom, Notepad++
3. Browser based Notebooks - Jupyter Notebook, Google Colab
4. Command-Line Interface (CLI) - IPython, Python REPL (Read-Eval-Print Loop)

1.3.1 Essen als of Python Programming

Python is a versa le and widely-used programming language known for its readability and simplicity.
Understanding the essen als of Python programming is crucial for beginners and advanced users alike.
The key essen als below, provide a strong founda on for Python programming. Whether you’re
developing simple scripts or complex applica ons, mastering these concepts will enable you to write
efficient, readable, and powerful Python code.

1. Syntax and Structure –


a. Indenta on: Python uses indenta on (whitespace) to define the structure of code
blocks, such as loops, func ons, and condi onals. Proper indenta on is crucial since it
replaces braces {} used in other languages.

Algorithm Thinking with Python – Module1 Prepared by:


14 | P a g e Harish Kumar B, APME, CET
b. Comments: Use # for single-line comments and triple quotes """ ... """ or ''' ... ''' for
mul -line comments or doc strings.

2. Data Types and Variables -


a. Basic Data Types: Python includes several built-in data types like int, float, str (string),
bool (boolean), and NoneType.

b. Dynamic Typing: Python is dynamically typed, meaning you don’t need to declare the
type of a variable explicitly. The type is determined at run me.

c. Type Conversion: You can convert between types using func ons like int(), float(), str(),
etc.

3. Control Flow -
a. Condi onals: Python supports if, elif, and else statements for decision-making.

Algorithm Thinking with Python – Module1 Prepared by:


15 | P a g e Harish Kumar B, APME, CET
b. Loops: Python provides for and while loops for itera on.

c. Loop Control: Use break, con nue, and pass to control loop execu on.

4. Func ons and Modules -


a. Defining Func ons: Use the def keyword to define func ons.

Algorithm Thinking with Python – Module1 Prepared by:


16 | P a g e Harish Kumar B, APME, CET
b. Modules: Python’s modular design allows you to organize code into modules (files) and
packages (directories of modules). Use import to include modules.

5. Data Structures

Algorithm Thinking with Python – Module1 Prepared by:


17 | P a g e Harish Kumar B, APME, CET
6. Object-Oriented Programming (OOP)
Classes and Objects: Python supports OOP concepts like classes, inheritance, and
polymorphism.

7. File Handling
Reading and Wri ng Files: Python provides built-in func ons to read from and write to
files.

8. Excep on Handling
Try-Except Blocks: Python handles errors using try, except, and op onally finally.

9. Libraries and Frameworks

Algorithm Thinking with Python – Module1 Prepared by:


18 | P a g e Harish Kumar B, APME, CET
a. Standard Library: Python has a rich standard library with modules for various tasks, such
as math, os, date me, and more.

b. Third-Party Libraries: Python has extensive third-party libraries available through the
Python Package Index (PyPI), including pandas for data analysis, numpy for numerical
computa ons, and requests for HTTP requests.

Mastering these 9 essen als will provide a strong founda on for Python programming. Whether you're
working on simple scripts or complex applica ons, understanding these concepts will enable you to
write efficient, readable, and powerful Python code.

1.3.2 Crea ng and using Variables in Python

In Python, variables are used to store data that can be referenced and manipulated throughout a
program. Crea ng and using variables in Python is straigh orward and forms the basis for storing and
manipula ng data in your programs. Understanding variable assignment, types, and scope is essen al
for wri ng clear and effec ve Python code.

1. Crea ng Variables

Syntax - Variables are created by assigning a value to a name using the = operator.

Example: x = 10

2. Naming Rules:

Must start with a le er or underscore (_), but cannot start with a number.

Can contain le ers, numbers, and underscores.

Spaces are not allowed in variable names (use underscores instead, like my_variable).

Case-sensi ve (e.g., myVariable and myvariable are different).

3. Using Variables in Python


o Accessing Values - Once a variable is created, you can use its name to access and
manipulate the stored value.
 Example: print(x) would output 10 if x was assigned 10.
o Changing Values - Variables can be reassigned new values at any me.
 Example: x = 20 would change the value of x from 10 to 20.
o Input Func on - The input() func on allows you to get user input and store it in a
variable.
 Example: name = input("Enter your name: ") will prompt the user to enter their
name and store it in the variable name.
o Print Func on - The print() func on is used to display the value of variables.
 Example: print("Hello, " + name) will output a gree ng with the user's name.
4. Types of Variables in Python
o Integer:
 Example: age = 25

Algorithm Thinking with Python – Module1 Prepared by:


19 | P a g e Harish Kumar B, APME, CET
o Float:
 Example: height = 5.9
o String:
 Example: name = "Alice"
o Boolean:
 Example: is_student = True

o Complex Number:
 Example: z = 3 + 4j (where j is the imaginary unit)
o None Type:
 Example: value = None (used to represent the absence of a value or a null
value)
5. Mul ple Assignment in Python
o Assigning Mul ple Variables at Once - Python allows you to assign values to mul ple
variables in a single line.
 Example: a, b, c = 1, 2, 3 assigns 1 to a, 2 to b, and 3 to c.
o Mul ple Input - You can also use mul ple assignment with the input() func on to get
mul ple inputs from the user at once.
 Example: x, y = map(int, input("Enter two numbers separated by a space:
").split())
 This will prompt the user to input two numbers separated by a space and
convert them to integers before assigning them to x and y.
6. Variable Scope
 Global Variables - Defined outside of any func on and accessible throughout the
program.
 Local Variables - Defined inside a func on and accessible only within that func on.
7. Python Cas ng
Python cas ng refers to the process of conver ng a variable from one data type to another. This
is useful when you need to perform opera ons that require a specific data type, or when you
want to ensure that your data is in the correct format.

Algorithm Thinking with Python – Module1 Prepared by:


20 | P a g e Harish Kumar B, APME, CET
1.3.3 Numerical Operators in Python

Python provides a variety of numerical operators for performing arithme c opera ons on numbers.
These operators work with both integers and floa ng-point numbers.

Algorithm Thinking with Python – Module1 Prepared by:


21 | P a g e Harish Kumar B, APME, CET
Algorithm Thinking with Python – Module1 Prepared by:
22 | P a g e Harish Kumar B, APME, CET
Algorithm Thinking with Python – Module1 Prepared by:
23 | P a g e Harish Kumar B, APME, CET
Programming Exercise on variable types in Python E1

1. Write a Python program that prints "Hello, World!" to the console.


2. How would you use a single-line comment to describe the purpose of a variable in Python?
3. Write a Python program that prints a mul -line message using triple quotes (""").
4. Create a variable x and assign it the value 10. Print the value of x.
5. Write a Python program to declare an integer variable, a float variable, and a string variable,
and print them.
6. How can you take a user’s name as input and print a personalized gree ng in Python?
7. Write a Python program that takes two numbers as input from the user and assigns them to
variables a and b in a single line.
8. Given x = "100", use Python cas ng to convert x to an integer and print its type using the type()
func on.
9. Write a program that prompts the user to input their age and then prints whether they are an
adult (18 or older) or a minor.
10. Demonstrate the use of a global variable and a local variable with the same name in a Python
func on.
11. Write a Python program that swaps the values of two variables a and b using mul ple
assignment.
12. Create a Python script that reads three integers from the user in a single line and calculates
their sum.
13. What will be the output of print(type(3.5)) in Python?
14. Write a Python program to check if a variable y is of type string and print the result.
15. How can you use mul -line comments to temporarily disable a block of code in Python?
16. Write a Python program that takes a string input from the user and prints its length using the
len() func on.
17. Given a variable z = 7.89, use Python cas ng to convert z to an integer and a string, then print
both.
18. Explain the difference between local and global variables in Python with an example.
19. Write a Python program that prints the type of a variable a er taking input from the user and
cas ng it to a float.
20. How can you use the input() func on to take a name and age from the user in a single line and
print a message that includes both?
21. Write a Python program that calculates how many complete hours are in 5500 seconds using
floor division. What is the result?
22. Given a number of total minutes, write a Python program to calculate how many minutes are
le a er conver ng the total minutes to hours. For example, if you have 123 minutes, how
many minutes remain a er conver ng to hours?

Algorithm Thinking with Python – Module1 Prepared by:


24 | P a g e Harish Kumar B, APME, CET
23. Write a Python program that calculates the cube of a given number using the exponen a on
operator. For example, if the number is 4, what is 4 raised to the power of 3?
24. What are the final values of x and y a er execu ng these lines of code?

25. What are the final values of x and y a er execu ng these lines of code?

1.3.3.1 Python Assignment Operators

In addi on to the basic assignment operator (=), Python supports several compound assignment
operators that combine arithme c opera ons with assignment. Here is how each of these operators.

Algorithm Thinking with Python – Module1 Prepared by:


25 | P a g e Harish Kumar B, APME, CET
Algorithm Thinking with Python – Module1 Prepared by:
26 | P a g e Harish Kumar B, APME, CET
1.3.3.2 Comparison Operators

Purpose: Used to compare two values and return a Boolean result (True or False).

Algorithm Thinking with Python – Module1 Prepared by:


27 | P a g e Harish Kumar B, APME, CET
1.3.3.3 Logical Operators

Purpose: Used to combine condi onal statements and return a Boolean result.

1.3.4 Using strings in Python

Strings in Python are sequences of characters enclosed in quotes. They are immutable, meaning that
their content cannot be changed a er crea on.

1.3.4.1 Slicing Strings

Slicing allows you to extract a por on of a string using indices. The syntax is:

Algorithm Thinking with Python – Module1 Prepared by:


28 | P a g e Harish Kumar B, APME, CET
1.3.4.2 Important String Func ons

len(): Returns the length of the string.

Algorithm Thinking with Python – Module1 Prepared by:


29 | P a g e Harish Kumar B, APME, CET
Algorithm Thinking with Python – Module1 Prepared by:
30 | P a g e Harish Kumar B, APME, CET
1.3.4.3 Characteris cs of Strings Compared to Other Variables

1. Immutability: Strings are immutable, meaning their content cannot be altered a er crea on.
This is in contrast to mutable types like lists or dic onaries.

2. Concatena on and Repe on: Strings support concatena on and repe on using + and *
operators, respec vely.

3. String Forma ng: Strings support various forma ng methods to include variables and
expressions.

Algorithm Thinking with Python – Module1 Prepared by:


31 | P a g e Harish Kumar B, APME, CET
Programming Exercise on Python Strings E2

1. Given a string s = "Hello, World!", write a Python program to extract the substring "World" using
slicing.
2. If s = "abcdefg", write a Python program to reverse the string using slicing.
3. Given a string s = "PythonProgramming", write a Python program to extract every second
character star ng from the first character using slicing.
4. Given a string s = "123456789", write a Python program to extract the substring "13579" using
slicing with a step value.
5. Given a string s = "abcdefgh", write a Python program to slice the string so that it returns "gfe".
6. Write a Python program to find the length of the string s = "Python" using the len() func on.
7. Given a string s = " Hello, World! ", write a Python program to remove the leading and trailing
spaces using the strip() func on.
8. Write a Python program that converts the string s = "python programming" to uppercase using
the upper() func on.
9. Given a string s = "Hello, World!", write a Python program to replace the substring "World" with
"Python" using the replace() func on.
10. Write a Python program that splits the string s = "apple,banana,cherry" into a list of fruits using
the split() func on and the comma , as a separator.

1.3.5 Python Collec ons: List, Tuple, Set, and Dic onary

Python offers four main collec on data types: List, Tuple, Set, and Dic onary. Each of these has unique
characteris cs and is suited to specific applica ons. Each collec on type has its strengths and specific
use cases, allowing Python to be versa le in handling various types of data structures effec vely.

1.3.5.1 Python Collec ons: List

A list is an ordered, mutable collec on of elements. It allows duplicate elements and can store elements
of different data types (e.g., integers, strings, lists).

o Syntax:

o Key Features:
 Order: Lists maintain the order of elements as they are inserted.

Algorithm Thinking with Python – Module1 Prepared by:


32 | P a g e Harish Kumar B, APME, CET
 Mutability: Elements can be added, removed, or modified.
 Indexing: Supports indexing and slicing.
o Applica ons:
 Dynamic Arrays: Where elements need to be added or removed frequently.
 Itera ve Opera ons: When you need to loop through elements and possibly
modify them.

1.3.5.2 Python Collec ons: Tuple

A tuple is an ordered, immutable collec on of elements. Like lists, tuples can store elements of different
data types but do not allow modifica on a er crea on.

o Syntax:

o Key Features:
 Order: Tuples maintain the order of elements.
 Immutability: Once created, elements cannot be added, removed, or changed.
 Indexing: Supports indexing and slicing, similar to lists.
o Applica ons:
 Fixed Data: Ideal for storing fixed collec ons of items, such as coordinates,
where data should not change.
 Dic onary Keys: Tuples can be used as keys in dic onaries since they are
immutable.

1.3.5.3 Python Collec ons: Set

A set is an unordered, mutable collec on of unique elements. Sets automa cally discard duplicate
values and do not maintain any specific order.

o Syntax:

o
o Key Features:
 Unordered: Elements do not have a specific order.
 Unique: No duplicate elements allowed.
 Mutability: Elements can be added or removed, but the set itself is mutable.
o Applica ons:
 Membership Tes ng: Fast checks to see if an element exists in a collec on.
 Removing Duplicates: Ideal for removing duplicates from a list or other
collec ons.
 Set Opera ons: Useful for performing mathema cal set opera ons like union,
intersec on, and difference.

Algorithm Thinking with Python – Module1 Prepared by:


33 | P a g e Harish Kumar B, APME, CET
1.3.5.4 Python Collec ons: Dic onary

A dic onary is an unordered collec on of key-value pairs. Each key must be unique, but the values can
be duplicated. Dic onaries are mutable, allowing modifica on of their keys and values.

o Syntax:

o
o Key Features:
 Unordered: No specific order for keys and values.
 Unique Keys: Each key must be unique, but values can be repeated.
 Mutability: Keys and values can be added, modified, or removed.
 Indexing by Key: Access values by using their keys.
o Applica ons:
 Data Mapping: When you need to map unique keys to values, like storing user
informa on.
 Lookups: Quick access to data using keys, such as configura on se ngs or
lookup tables.
 Coun ng Occurrences: Used to count occurrences of items, where the item is
the key and the count is the value.

1.3.5.5 Python Collec ons: Comparison

Programing Exercise on Python Collec ons –E3

1. Given a list my_list = [1, 2, 3], write a Python program to append the element 4 to the list using
the append() method.
2. Write a Python program to remove the first occurrence of the element 2 from the list my_list =
[1, 2, 2, 3] using the remove() method.
3. Given a list my_list = [5, 10, 15, 20, 25], write a Python program to use the pop() method to
remove and return the last element of the list.
4. Write a Python program to insert the element 100 at index 2 in the list my_list = [1, 2, 3, 4] using
the insert() method.

Algorithm Thinking with Python – Module1 Prepared by:


34 | P a g e Harish Kumar B, APME, CET
5. Given a list my_list = [3, 1, 4, 1, 5, 9], write a Python program to sort the list in ascending order
using the sort() method.
6. Write a Python program to create a tuple my_tuple containing the elements 1, 2, 3, 4, 5. Then,
use slicing to print the first three elements of the tuple.
7. Given a tuple my_tuple = (10, 20, 30, 40), write a Python program to find the index of the
element 30 using the index() method.
8. Write a Python program to count the number of mes the element 2 appears in the tuple
my_tuple = (1, 2, 2, 3, 4) using the count() method.
9. Given a tuple my_tuple = (1, 2, 3, 4, 5), write a Python program to unpack the tuple into five
individual variables.
10. Write a Python program to create a new tuple by concatena ng the two tuples t1 = (1, 2) and
t2 = (3, 4).
11. Given a set my_set = {1, 2, 3}, write a Python program to add the element 4 to the set using the
add() method.
12. Write a Python program to remove the element 2 from the set my_set = {1, 2, 3, 4} using the
discard() method. What happens if the element does not exist in the set?
13. Given two sets set1 = {1, 2, 3} and set2 = {3, 4, 5}, write a Python program to find the intersec on
of these sets using the intersec on() method.
14. Write a Python program to find the difference between two sets set1 = {1, 2, 3, 4} and set2 =
{3, 4, 5, 6} using the difference() method.
15. Given a set my_set = {1, 2, 3, 4}, write a Python program to clear all elements from the set using
the clear() method.
16. Given a dic onary my_dict = {"name": "Alice", "age": 25, "city": "New York"}, write a Python
program to add a new key-value pair "email": "[email protected]" using the update() method.
17. Write a Python program to remove the key "age" and its value from the dic onary my_dict =
{"name": "Alice", "age": 25, "city": "New York"} using the pop() method. What is the return value
of the pop() method?
18. Given a dic onary my_dict = {"a": 1, "b": 2, "c": 3}, write a Python program to retrieve the value
associated with the key "b" using the get() method. What happens if you try to retrieve a key
that does not exist in the dic onary?
19. Write a Python program to iterate through the dic onary my_dict = {"name": "Alice", "age": 25,
"city": "New York"} and print both the keys and values using the items() method.
20. Given a dic onary my_dict = {"a": 1, "b": 2, "c": 3}, write a Python program to check if the key
"c" exists in the dic onary using the in keyword.

1.3.6 Using the math module

The Python math module provides various mathema cal func ons that are useful for performing
calcula ons. Math Module consists of mathema cal func ons and constants. It is a built-in module
made for mathema cal tasks. So no need to install it separately using pip. It is available as part of the
Python Standard Library, which means you can import it directly without any external installa on. These
func ons are highly useful for mathema cal computa ons, and they cover a wide range of scenarios
from basic arithme c to more complex opera ons like trigonometry, logarithms, and factorials.

Algorithm Thinking with Python – Module1 Prepared by:


35 | P a g e Harish Kumar B, APME, CET
Some of the important things you can do with the math module include,

a. Basic Mathema cal Opera ons

Algorithm Thinking with Python – Module1 Prepared by:


36 | P a g e Harish Kumar B, APME, CET
b. Trigonometric Func ons

Algorithm Thinking with Python – Module1 Prepared by:


37 | P a g e Harish Kumar B, APME, CET
Algorithm Thinking with Python – Module1 Prepared by:
38 | P a g e Harish Kumar B, APME, CET
c. Exponen al and Logarithmic Func ons

Algorithm Thinking with Python – Module1 Prepared by:


39 | P a g e Harish Kumar B, APME, CET
d. Constants

Programming Exercise on math module in Python

1. Write a Python program to find the ceiling value of a given floa ng-point number.
2. Write a Python program to calculate the factorial of a given integer.
3. Write a Python program to find the greatest common divisor (GCD) of two numbers.
4. Write a Python program to convert an angle from degrees to radians.

Algorithm Thinking with Python – Module1 Prepared by:


40 | P a g e Harish Kumar B, APME, CET
5. Write a Python program to calculate the square root of a given number.
6. Write a Python program to find the absolute value of a given number.
7. Write a Python program to find the sine, cosine, and tangent of a given angle in radians.
8. Write a Python program to calculate e raised to the power of a given number.
9. Write a Python program to compute the natural logarithm (base e) of a given number.
10. Write a Python program to calculate the LCM (Least Common Mul ple) of two numbers using
the gcd() func on.

1.3.7 Using the Python Standard Library for handling file I/O

The Python Standard Library provides several modules for handling file I/O (Input/Output), which allow
you to read from and write to files, interact with the file system, and handle various file formats.

The file handling plays an important role when the data needs to be stored permanently into the file. A
file is a named loca on on disk to store related informa on. We can access the stored informa on (non-
vola le) a er the program termina on. In Python, files are treated in two modes as text or binary. The
file may be in the text or binary format, and each line of a file is ended with the special character like a
comma (,) or a newline character.

a. Basic File Opera ons (open(), read(), write(), close())


At the core of file handling in Python is the open() func on, which is used to open files and
return a file object.
Opening a file

'mode' specifies how the file should be opened:


 'r' (Read) - Opens a file for reading (default mode).
 'w' (Write) - Opens a file for wri ng. Creates the file if it doesn’t exist or
truncates the file if it exists.
 'a' (Append - Opens a file for appending data to the end.
 'b' (Binary) - Opens the file in binary mode (e.g., 'rb' for reading a binary
file).
 '+' (Update) - Opens a file for both reading and wri ng.

Reading a file

 read(): Reads the en re file as a string.


 readline(): Reads one line at a me.
 readlines(): Reads all lines into a list.

Algorithm Thinking with Python – Module1 Prepared by:


41 | P a g e Harish Kumar B, APME, CET
Wri ng to a file

 write(): Writes a string to the file.


 writelines(): Writes a list of strings to the file.

b. Context Manager for File I/O (with statement)


Using the ‘with’ statement is considered the best prac ce when dealing with files, as it
automa cally closes the file a er the block of code is executed, even if an excep on occurs.

c. File Path Handling (os and pathlib modules)


 os module
 os.path.exists(path): Check if a file exists.
 os.remove(path): Delete a file.
 os.rename(src, dest): Rename a file.

Programming Exercise on Python Standard Library for handling file I/O – E6

Algorithm Thinking with Python – Module1 Prepared by:


42 | P a g e Harish Kumar B, APME, CET
1) Write a Python program to open a text file, read its contents, and display it on the screen using basic
file opera ons (open(), read(), and close()).
2) How can you write mul ple lines of text to a file and then read them back using the with statement
to manage file resources?
3) Create a Python program that appends a new line of text to an exis ng file using the 'a' mode. A er
appending, read the en re file and display the contents.
4) Using the os module, write a program that checks if a specific file exists in the current directory and
deletes it if it does.
5) Write a Python script using the pathlib module that lists all files in a directory and checks if a given
file path is a file or a directory.
6) How would you rename a file in Python using the os module? Write a program that renames a file
from old_name.txt to new_name.txt.
7) Write a Python func on that takes a file path as input, reads its contents, and returns the number
of words in the file using the with statement for file handling.
8) Using the pathlib module, write a Python script that creates a new directory, creates a file inside
that directory, and writes some content to it.

1.3.8 Using the NumPy library

NumPy (Numerical Python) is a powerful Python library used for numerical compu ng. It provides
support for working with large, mul -dimensional arrays and matrices, along with a collec on of high-
level mathema cal func ons to operate on these arrays. NumPy is a core component in scien fic
compu ng and data analysis, forming the founda on for libraries like Pandas, SciPy, and machine
learning frameworks like TensorFlow.

1.3.8.1 Key Features:

1. N-Dimensional Array Object - Central to NumPy is the ndarray, a mul -dimensional container
for homogeneous data (i.e., all elements must be of the same type). This array can be used to
perform vectorized opera ons, avoiding loops and speeding up computa ons.
2. Broadcas ng - NumPy allows for element-wise opera ons on arrays of different shapes, a
technique called broadcas ng. This makes it easier to perform opera ons between arrays
without needing them to be the same shape.
3. Mathema cal Func ons - It includes func ons for basic linear algebra, Fourier transforms,
sta s cal opera ons, and more.
4. Efficient Array Opera ons - NumPy's opera ons are highly op mized, as they are implemented
in C, making it much faster than pure Python lists for numerical tasks.
5. Integra on with Other Libraries - It integrates well with other scien fic compu ng libraries in
Python (such as Pandas, Matplotlib, and SciPy).

1.3.8.2 Advantages of NumPy:

1. Performance - NumPy arrays are more efficient than Python lists, par cularly for large datasets,
due to their fixed size and type, and the fact that opera ons are done in compiled C code.
2. Memory Efficiency - NumPy uses less memory than Python lists because it stores data in
con guous blocks and avoids the overhead associated with Python’s object storage.
3. Convenience - It simplifies array-based calcula ons and opera ons, including slicing, indexing,
reshaping, and broadcas ng, which are difficult to perform with lists.

Algorithm Thinking with Python – Module1 Prepared by:


43 | P a g e Harish Kumar B, APME, CET
4. Large Community and Ecosystem - Being a widely-used library, it has a vast community, thorough
documenta on, and is the backbone for many other libraries in the Python data science
ecosystem.
5. Support for Mul dimensional Data- While Python lists are inherently one-dimensional, NumPy
can handle mul -dimensional arrays, allowing for complex data manipula on and
computa onal tasks.

1.3.8.3 Basic func ons, and a ributes in NumPy.

a. Impor ng NumPy

Import the numpy library before you can use its func ons.

b. Declaring an Array

Using a List to Create a NumPy Array

This creates a 2D array.

c. Array A ributes
Once array is created various a ributes of NumPy can be accessed.

Algorithm Thinking with Python – Module1 Prepared by:


44 | P a g e Harish Kumar B, APME, CET
d. Array Crea on Func ons
np.zeros(): Creates an array filled with zeros.

np.ones(): Creates an array filled with ones.

Algorithm Thinking with Python – Module1 Prepared by:


45 | P a g e Harish Kumar B, APME, CET
e. Using arange() Func on
The ‘arange’ func on generates an array with evenly spaced values within a given range.

f. Reshaping an Array
Use reshape() to change the shape of an array without changing its data

g. Minimum Dimensions (ndmin A ribute)

h. Array Func ons


np.sum(): Returns the sum of all elements.
np.max() and np.min(): Returns the maximum and minimum value of the array.
np.mean(): Returns the mean of the array.

Algorithm Thinking with Python – Module1 Prepared by:


46 | P a g e Harish Kumar B, APME, CET
i. Scalar Mul plica on

j. Matrix Mul plica on


For matrix mul plica on (dot product), use np.dot() or the @ operator and for cross product
use np.cross()

k. Element-wise Mul plica on (Hadamard Product)

Algorithm Thinking with Python – Module1 Prepared by:


47 | P a g e Harish Kumar B, APME, CET
l. Transpose of a Matrix

m. Cross Product of Vectors

n. Inverse of a Matrix

o. Determinant of a Matrix

Algorithm Thinking with Python – Module1 Prepared by:


48 | P a g e Harish Kumar B, APME, CET
p. Eigenvalues and Eigenvectors

1.3.8.4 Basic random func ons in NumPy.

NumPy provides several useful func ons to generate random numbers, which are part of the
numpy.random module.

a. ‘rand()’ - Uniform Distribu on - Generates random numbers between 0 and 1 (from a uniform
distribu on).

b. ‘randn()’ - Normal Distribu on - Generates random numbers from a standard normal


distribu on (mean = 0, standard devia on = 1).

c. ‘randint()’ - Random Integers - Generates random integers from a specified range.

Algorithm Thinking with Python – Module1 Prepared by:


49 | P a g e Harish Kumar B, APME, CET
d. ‘choice()’ - Random Selec on from Array - Selects random elements from a given array.

e. ‘shuffle()’ - Randomly Shuffle Array - Shuffles the elements of an array in place.

f. ‘seed()’ - Se ng the Seed - The seed() func on is used to set the seed for random number
genera on, ensuring reproducibility.

Algorithm Thinking with Python – Module1 Prepared by:


50 | P a g e Harish Kumar B, APME, CET
1.3.8.5 NumPy slicing

NumPy slicing allows you to extract specific elements, rows, columns, or subarrays from a NumPy array
using slice nota on. The basic syntax for slicing in NumPy is:

Algorithm Thinking with Python – Module1 Prepared by:


51 | P a g e Harish Kumar B, APME, CET
Algorithm Thinking with Python – Module1 Prepared by:
52 | P a g e Harish Kumar B, APME, CET
Algorithm Thinking with Python – Module1 Prepared by:
53 | P a g e Harish Kumar B, APME, CET
Programming Exercise on Numpy module in Python

1) Write a Python program to create a 1D NumPy array of 10 integers and perform basic arithme c
opera ons like addi on, subtrac on, mul plica on, and division on the array.
2) Write a Python program to create a 5x5 iden ty matrix using NumPy.
3) Generate a NumPy array of 20 random integers between 50 and 150, then find the mean, median,
and standard devia on.
4) Create a 1D NumPy array of integers and reshape it into a 3x4 matrix. Print the original and reshaped
arrays.
5) Write a Python program to slice a 2D NumPy array and extract specific rows and columns.
6) Create two NumPy arrays and perform matrix mul plica on. Verify the result using both the @
operator and np.dot().
7) Write a Python program to generate an array of 100 evenly spaced numbers between 0 and 10
using linspace().
8) Write a Python program to find the unique elements and their frequencies in a given NumPy array.
9) Create a 4x4 matrix filled with random numbers and replace all numbers greater than 10 with 10.
10) Write a Python program to concatenate two NumPy arrays horizontally and ver cally.
11) Write a Python program to find the sum of all elements, row-wise and column-wise, in a given 2D
NumPy array.
12) Create a NumPy array of 50 random floats and round all the numbers to 2 decimal places.
13) Write a Python program to find the inverse and determinant of a 3x3 matrix using NumPy.
14) Generate two random NumPy arrays and compute their element-wise maximum and minimum.
15) Create a 5x5 matrix of random integers and sort it row-wise and column-wise.

Algorithm Thinking with Python – Module1 Prepared by:


54 | P a g e Harish Kumar B, APME, CET

You might also like