0% found this document useful (0 votes)
3 views14 pages

Module 1 ATP

The document provides an overview of algorithmic thinking and problem-solving strategies using Python, covering essential concepts such as trial and error, algorithms, heuristics, means-ends analysis, and backtracking. It outlines the problem-solving process, including understanding the problem, formulating a model, developing algorithms, and programming in Python. Additionally, it introduces Python programming essentials, including data types, variable creation, the math module, and file handling techniques.

Uploaded by

Reji
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)
3 views14 pages

Module 1 ATP

The document provides an overview of algorithmic thinking and problem-solving strategies using Python, covering essential concepts such as trial and error, algorithms, heuristics, means-ends analysis, and backtracking. It outlines the problem-solving process, including understanding the problem, formulating a model, developing algorithms, and programming in Python. Additionally, it introduces Python programming essentials, including data types, variable creation, the math module, and file handling techniques.

Uploaded by

Reji
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/ 14

Algorithmic Thinking with Python- Notes

Module 1: (7 hrs)

PROBLEM-SOLVING STRATEGIES:- Problem-solving strategies defined, Importance of


understanding multiple problem-solving strategies, Trial and Error, Heuristics, Means-Ends
Analysis, and Backtracking (Working backward).
THE PROBLEM SOLVING PROCESS: Computer as a model of computation, Understanding
the problem, Formulating a model, Developing an algorithm, Writing the program, Testing the
program, and Evaluating the solution.
ESSENTIALS OF PYTHON PROGRAMMING - Creating and using variables in Python,
Numeric and String data types in Python, Using the math module, Using the Python Standard
Library for handling basic I/O - print, input, Python operators and their precedence.

Module 1.1 (2 hrs)

PROBLEM-SOLVING STRATEGIES:- Problem-solving strategies defined, Importance of


understanding multiple problem-solving strategies, Trial and Error, Heuristics, Means-
Ends Analysis, and Backtracking (Working backward).

Problem-Solving Strategies
People face problems every day—usually, multiple problems throughout the day.
Eg: Food prepared not enough, Printer not working for an urgent report
Identify the problem and then apply a strategy for solving the problem.

Definition: A problem-solving strategy is a plan of action used to find a solution.


Different strategies have different action plans associated with them.

Importance of Understanding Multiple Problem-solving Strategies

Problems can be classified into two different categories:


1)Ill-defined problems : Ill-defined problems represent issues that do not have clear
goals, solution paths, or expected solutions
2) Well-defined problems: well-defined problems have specific goals, clearly defined
solutions, and clear expected solutions.

Methods of studying problem solving includes introspection, simulation, computer modelling,


and experimentation.
Understanding how a variety of problem-solving strategies work is important because different
problems typically require you to approach them in different ways to find the best solution.

1
Important problem-solving strategies are Trial and Error, Algorithms, Heuristics, Means-Ends
Analysis, and Backtracking (Working backward).

1) Trial and error


A trial-and-error approach to problem-solving involves trying a number of different solutions
and eliminating those that do not work.
Eg: Printer not working: check ink level, paper tray, connection

Trial and error is not typically one of the most time-efficient strategies, it is a commonly used
one.

2)Algorithm
An algorithm is a problem-solving formula that provides step-by-step instructions used to
achieve a desired outcome.
Detailed instructions that produce the same result every time they are performed.
Eg: Google: Which link first?
Facebook: which posts to display on the newsfeed

3) Heuristic
A heuristic is a general problem-solving framework
As mental shortcuts that are used to solve problems. A “rule of thumb” is an example of a
heuristic.
Such a rule saves the person’s time and energy when making a decision, but, it is not always the
best method for making a rational decision.

Heuristic is used when one of five conditions is met:


1)When one is faced with too much information
2)When the time to make a decision is limited
3) When the decision to be made is unimportant
4)When there is access to very little information to use in making the decision
5)When an appropriate heuristic happens to come to mind in the same moment

2
Eg: working backwards heuristic: to reach a wedding at 12.pm
Another useful heuristic is the practice of accomplishing a large goal or task by breaking it into a
series of smaller steps like completing a project

4)Means-end analysis
This strategy involves choosing and analysing an action at a series of smaller steps to move
closer to the goal.
Eg: Tower of Hanoi paradigm.
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack or on an empty rod.
3. No larger disc may be placed on top of a smaller disk.
For example, a student might be faced with the problem of how to successfully get through
exam.
Current state: They haven’t started studying,
end goal: to pass the exams.
A solution: putting their phone on “do not disturb” mode while studying

Method Description Example

Restarting phone, turning off WiFi, turning off


Trial and Continue trying different solutions
bluetooth in order to determine why your phone is
error until problem is solved
malfunctioning

Step-by-step problem-solving Instruction manual for installing new software on


Algorithm
formula your computer

General problem-solving
Heuristic Working backwards; breaking a task into steps
framework

Analysing a problem at series of


Means-ends Envisioning the ultimate goal and determining the
smaller steps to move closer to the
analysis best strategy for attaining it in the current situation
goal

5)Backtracking
Backtracking is a problem-solving algorithmic technique that involves finding a solution
incrementally by trying different options and undoing them if they lead to a dead end.

3
Eg: Searching for a path in a maze or solving puzzles like Sudoku.

Module 1.2 (2 hrs)

THE PROBLEM SOLVING PROCESS - Computer as a model of computation,


Understanding the problem, Formulating a model, Developing an algorithm, Writing the
program, Testing the program, and Evaluating the solution.

Computer as a model of computation


Computers are used for solving various day-to-day problems. Precise step-by-step instructions
should be given by us to solve the problem.
A typical single CPU computer processes information as shown in the diagram. Problems are
solved using a computer by obtaining some kind of user input (e.g., keyboard/mouse information
or game control movements), then processing the input and producing some kind of output (e.g.,
images, text, sound). Sometimes the incoming and outgoing data may be in the form of hard
drives or network devices.

4
Definition: Problem Solving is the sequential process of analysing information related to a given
situation and generating appropriate response options.

Example: Calculate the average grade for all students in a class.


1. Input: get all the grades.
2. Process: add them all up and compute the average grade.
3. Output: output the answer to either the monitor, to the printer, etc.

In solving a problem, there are some well-defined steps to be followed:

1. Understanding/Analyzing the Problem


The first step to solving any problem is to make sure that one understands the
problem about to be solved
 What input data/information is available?
▪ What does the data/information represent?
▪ In what format is the data/information?
▪ What is missing in the data provided?
▪ What output information needs to be produced?
▪ In what format should the result be: text, picture, graph?

5
2. Formulating a Model
Understand the processing part of the problem.
Figuring out how to make use of the available data to compute an answer
Broad overview of the sequence of operations that are to be carried out to solve
the given problem
Eg. for a model: 1 = ( 1 + 2 + 3 + ⋯ + )/

3. Developing an Algorithm
Having understood the problem and formulated a model, a precise plan of what
the computer is expected to do have to be developed.
Definition: Algorithm is a precise sequence of instructions for solving a problem.
Two commonly used representations for an algorithm is by using
(1) pseudocode: : pseudocode is a simple and concise sequence of
English-like instructions to solve a problem.
Pseudocode is often used as a way of describing a computer program to
someone who doesn’t understand how to program a computer
(2) flowcharts: A flowchart is a visual representation of an algorithm.
It is a diagram made up of boxes, diamonds and other shapes, connected
by arrows.

6
4. Writing the Program
Transform the algorithm into a set of instructions that can be understood by the
computer.
Writing a program is often called "coding" or “implementing an algorithm”.
So the code (or source code) is actually the program itself. Source code would
vary depending on the programming language.
Definition: Compiling is the process of converting a program into instructions that
can be understood by the computer.

5. Test the Program


Make sure the program solves the problem that it was intended to solve and that
the solutions are correct.
Definition: Bugs are errors with a program that cause it to stop working or
produce incorrect or undesirable results.
To find bugs effectively, a program should be tested with many test cases (called
a test suite)
Definition: Debugging is the process of finding and fixing errors in program code

6. Evaluating the Solution


Once the program produces a result that seems correct, the original problem needs
to be reconsidered to make sure that the answer is formatted into a proper solution
to the problem
There may be a need to display the information in a way that helps visualise or
interpret the results with respect to the problem; perhaps a chart or graph is
needed.

Module 1(C part)

7
ESSENTIALS OF PYTHON PROGRAMMING - Creating and using variables in Python,
Numeric and String data types in Python, Using the math module, Using the Python
Standard Library for handling basic I/O - print, input, Python operators and their
precedence.
Python
– general-purpose and interpreted : processed at runtime by the interpreter.
– Interactive
– object-oriented
– high-level programming language(Python2, Python3)
• It was created by Guido van Rossum during 1985-1990.
Properties
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax
• Easy-to-read
• Easy-to-maintain
• A broad standard library: Python's library is very portable and cross-platform
compatible
• Interactive
• Portable: Python can run on different hardware platforms
• Automatic garbage collection.
Python files have extension .py.
Eg: Save this file as hello.py: print "Hello, Python!”
To execute: python hello.py
Python Identifiers
• a name used to identify a variable, function, class, module or other object.
• starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).
• does not allow punctuation characters such as @, $, and % within identifiers.
• Case sensitive programming language.
– sum and Sum are two different identifiers in Python.
Python keywords

8
Indentation
Python provides no braces to indicate blocks of code for class and function definitions or
flow control.
• Blocks of code are denoted by line indentation
• The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount.
A hash sign (#) that is not inside a string literal begins a comment.
Eg: # This is a program for matrix multiplication
Python interpreter ignores them.
Variable
Reserved memory locations to store values.
Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory.
The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point assignment
name = “John” # An string assignment
Python allows to assign a single value to several variables simultaneously.
•a=b=c=1
• a, b, c = 1, 2, "john"
Standard Data Types

9
Numeric data type
• int: Int, or integer, is a whole number, positive or negative, without decimals
x =1
y = 35656222554887711
z = -3255522
• float : "floating point number" is a number, positive or negative, containing one or more
decimals.
x = 1.10
y = 35e3
z = -35.59
• complex : Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
String data type
Strings in Python are identified as a contiguous set of characters represented in the
quotation
Marks(single or double quotes).
• Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting
at 0
in the beginning of the string
• The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
Eg: str = 'Hello World!'
1)print str # Prints complete string
2)print str[0] # Prints first character of the string
3)print str[2:5] # Prints characters starting from 3rd to 5th
4)print str[2:] # Prints string starting from 3rd character
5)print str * 2 # Prints string two times
6)print str + "TEST" # Prints concatenated string
result
Hello World!

10
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
A statement is a unit of code that the Python interpreter can execute.
Eg: For example, the script
x=2
print( x)
An expression is a combination of values, variables, and operators.
Eg: x + 17

Python math Module


Python has a built-in module that you can use for mathematical tasks.
The math module has a set of methods and constants.
Eg: Calculating area of circle
import math
r=4
pie = math.pi
print(pie * r * r)

Mathematical function in Math Module

Returns the smallest integral value greater


ceil(x)
than the number

Returns the greatest integral value smaller


floor(x)
than the number

11
sqrt(x) returns the square root of the number.

Compute the greatest common divisor of 2


gcd(x, y)
numbers

Returns the sine of value passed as


sin(x)
argument

import math
a = 2.3
print ("The ceil of 2.3 is : ", end="")
print (math.ceil(a))
print ("The floor of 2.3 is : ", end="")
print (math.floor(a))

Using the Python Standard Library for handling basic I/O - print, input
The print() function prints the specified message to the screen.
The message can be a string, or any other object, the object will be converted into a string
before written to the screen.
print("Hello World")
The input() function allows to read user input.
x = input('Enter your name:')
print('Hello, ' + x)
Python Operator Precedence
An expression may have multiple operators to be evaluated. The operator precedence
defines the order in which operators are evaluated.
BODMAS rule is employed by Python interpreter for arithmetic operators, where
the brackets are evaluated first, the division and multiplication operators next, followed
by addition and subtraction operators.

12
File Handling
Allows users to handle files i.e., to read and write files
In Python, files can broadly be categorized into two types based on their mode of operation:
 Text Files: These store data in plain text format. Examples include .txt files.
 Binary Files: These store data in binary format, which is not human-readable.
Examples include images, videos, and executable files.

The functions used for file handling in Python are:


 open(): Opens a file and returns a file object.
 read(): Reads data from a file.
 write(): Writes data to a file.
 close(): Closes the file, releasing its resources.
 tell() returns the current position of the file pointer after reading.

Eg: “s1cse.txt” contains


Hello world
123 456

Opening a file: f = open(filename, mode)

Modes:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data,
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.

13
# Python code to illustrate read() mode
file = open("s1cse.txt", "r")
print (file.read())
print (file.read(5))
file.close()

# Python code to create a file


file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

# Python code to illustrate append() mode


file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()

14

You might also like