Algorithmic Thinking With Python Module 1 Class Note
Algorithmic Thinking With Python Module 1 Class Note
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
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,
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
Better
6 Enhances teamwork by sharing different approaches.
Collaboration
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
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.
Advantages Disadvantages
Encourages Creativity: Promotes innovative Time-Consuming: Can take a long time to find
thinking and problem-solving skills. the correct solution.
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.
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:
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
Algorithms are used in scenarios requiring precise and op mal solu ons, such as data processing,
network rou ng, and automated control systems.
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.
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.
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.
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.
Typical Examples where MEA is effec vely u lized for solu ons
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 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.
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.
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.
Key points:
What core components map a real computer to an abstract model of computa on?
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
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.
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.
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.
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. 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.
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.
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)
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.
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.
c. Loop Control: Use break, con nue, and pass to control loop execu on.
5. Data Structures
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.
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.
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.
Spaces are not allowed in variable names (use underscores instead, like my_variable).
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.
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.
25. What are the final values of x and y a er execu ng these lines of code?
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.
Purpose: Used to compare two values and return a Boolean result (True or False).
Purpose: Used to combine condi onal statements and return a Boolean result.
Strings in Python are sequences of characters enclosed in quotes. They are immutable, meaning that
their content cannot be changed a er crea on.
Slicing allows you to extract a por on of a string using indices. The syntax is:
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.
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.
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.
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.
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.
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. 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.
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.
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.
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.
Reading a file
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. 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. 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.
a. Impor ng NumPy
Import the numpy library before you can use its func ons.
b. Declaring an Array
c. Array A ributes
Once array is created various a ributes of NumPy can be accessed.
f. Reshaping an Array
Use reshape() to change the shape of an array without changing its data
n. Inverse of a Matrix
o. Determinant of a Matrix
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).
f. ‘seed()’ - Se ng the Seed - The seed() func on is used to set the seed for random number
genera on, ensuring reproducibility.
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:
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.