0% found this document useful (0 votes)
14 views36 pages

Python Notes Unit I

The document outlines a course on Problem Solving and Python Programming for B.Sc CS students, detailing objectives, course units, and outcomes. It covers topics such as algorithmic problem solving, Python data types, control flow, functions, and file handling. The course aims to equip students with the skills to develop algorithms, write Python programs, and manage data structures effectively.

Uploaded by

kavithar548
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)
14 views36 pages

Python Notes Unit I

The document outlines a course on Problem Solving and Python Programming for B.Sc CS students, detailing objectives, course units, and outcomes. It covers topics such as algorithmic problem solving, Python data types, control flow, functions, and file handling. The course aims to equip students with the skills to develop algorithms, write Python programs, and manage data structures effectively.

Uploaded by

kavithar548
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

I B.

Sc CS (Artificial Intelligence & Data Science)

I YEAR - II SEMESTER
PROBLEM SOLVING AND PYTHON
PROGRAMMING

STUDY MATERIAL
PROBLEM SOLVING AND PYTHON PROGRAMMING COURSE

OBJECTIVES:

□ To understand the basics of algorithmic problem solving.


□ To learn to solve problems using Python conditionals and loops.
□ To define Python functions and use function calls to solve problems.
□ To use Python data structures – lists, tuples, dictionaries to represent complex data.
□ To do input/output with files in Python.

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING

Fundamentals of Computing – Identification of Computational Problems -Algorithms, building


blocks of algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart,
programming language), algorithmic problem solving, simple strategies for developing
algorithms (iteration, recursion). Illustrative problems: find minimum in a list, insert a card in a list of
sorted cards, guess an integer number in a range, Towers of Hanoi.

UNIT II DATA TYPES, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators, comments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables,
distance between two points.

UNIT III CONTROL FLOW, FUNCTIONS, STRINGS

Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return
values,
parameters, local and global scope, function composition, recursion; Strings: string
slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative
programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary search

UNIT IV LISTS, TUPLES, DICTIONARIES

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;
advanced list processing – list comprehension; Illustrative programs: simple sorting,
histogram, Students marks statement, Retail bill preparation.

UNIT V FILES, MODULES, PACKAGES

Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs:
word count, copy file, Voter’s age validation, Marks range validation (0-100).

TOTAL : 45 PERIODS
COURSE OUTCOMES:

Upon completion of the course, students will be able to


CO1: Develop algorithmic solutions to simple computational problems.
CO2: Develop and execute simple Python programs.
CO3: Write simple Python programs using conditionals and looping for solving problems.
CO4: Decompose a Python program into functions.
CO5: Represent compound data using Python lists, tuples, dictionaries etc.
CO6: Read and write data from/to files in Python programs.

TEXT BOOKS: GE3151 Syllabus PROBLEM SOLVING AND PYTHON PROGRAMMING

1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition,
O’Reilly Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving
and programming”, 1st Edition, BCS Learning & Development Limited, 2017.

REFERENCES: GE3151 Syllabus PSPP

1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and
Data Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, "Introduction to Computation and Programming Using Python:
With Applications to Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press
2021
4. Eric Matthes, “Python Crash Course, A Hands – on Project Based Introduction to Programming”,
2nd Edition, No Starch Press, 2019.
5. [Link]
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
Algorithmic Problem Solving 1.1

Unit I

ALGORITHMIC PROBLEM SOLVING


Algorithms, building blocks of algorithms (statements, state, control
flow, functions), notation (pseudo code, flow chart, programming
language), algorithmic problem solving, simple strategies for
developing algorithms (iteration, recursion). Illustrative problems:
find minimum in a list, insert a card in a list of sorted cards, guess an
integer number in a range, Towers of Hanoi.

1.1 ALGORITHMS
What is algorithm?
An algorithm is a finite number of clearly described, unambiguous ―”doable”
steps that can be systematically followed to produce a desired result for given input in
a finite amount of time . Algorithms are the initial stage of problem solving. Algorithms
can be simply stated as a sequence of actions or computation methods to be done for
solving a particular problem. An algorithm should eventually terminate and used to
solve general problems and not specific problems.

Al-Khwarizmi

The word ―algorithm is derived from the ninth-century Arab mathematician,


Al-Khwarizmi. He worked on ―written processes to achieve some goal. Computer
1.2 Problem Solving and Python Programming
algorithms are central to computer science. They provide step-by-step methods of
computation that computers can carry out. High speed computers can follow a given
set of instructions for their computation which are programs. Programs are built from
algorithms. However, the computation that a given computer performs is only as good
as the underlying algorithm used.
Features
● An algorithm is a collection of well-defined, unambiguous and effectively
computable instructions, if execute it will return the proper output.
● Well-defined- The instructions given in an algorithm should be simple and
defined well.
● Unambiguous- The instructions should be clear,there should not be ambiguity .
● Effectively computable- The instructions should be written step by step ,which
helps computer to understand the control flow.
We often use algorithm in our day-to-day life, but when and how?
● Our cooking receipe
● Our daily routine as a student
● When we buy something
● When we go outing
● Our class routine
How it helps?
To understand the usage of algorithm, look over the following conversation.
Algorithmic Problem Solving 1.3

Lets discuss about the conversation,tom wants brush his teeth, so he asks chitti
to bring brush,what happens chitti returns cleaning brush.
Why this was happened ?
Because the statement given by tom was not well defined and it is ambiguous
statement so chitti get confused and bring some brush to [Link] is what happen if
the user gives ambiguity statement to the [Link] an algorithm should be
simple and well defined.
How an algorithm should be?
It should be in simple English, what a programmer wants to say. It has a start, a
middle and an end. Probably an algorithm should have,
Start
1. In the middle it should have set of tasks that computer wants to do and
it should be in simple English and clear.
2. To avoid ambiguous should give no for each step.
Stop

Lets look over the simple example,


The following algorithm helps the computer to validate user’s email address.
1.4 Problem Solving and Python Programming
Start
Create a variable to get the user’s email address clear the variable, incase
its not empty.
Ask the user for an email address.
Store the response in the variable.
Check the stored response to see if it is a valid email address Not valid?
Go back
Stop

Lets see how it works?

Why this Happened?


This was happened because the instructions given in an algorithm does not have
numbering for each [Link] Chitti gets confused which step have to do. To avoid this
ambiguity ,we should number each step while writing an algorithm.
So let’s rewrite the algorithm....
Algorithmic Problem Solving 1.5

Step1: Start
Step2: Create a variable to get the user’s email address
Step3: Clear the variable, incase its not empty.
Step4: Ask the user for an email address.
Step5: Store the response in the variable.
Step6: Check the stored response to see if it is a valid email address
Step7: Not valid? Go back
Step8: Stop

Suggested link to refer :


Link 1 [Link]
Link 2 [Link]
Link 3 [Link]

1.2 BUILDING BLOCKS OF ALGORITHMS


Building blocks are necessary to decide how we want to manipulate units of
work. The basis of every algorithm is steps or blocks of operations.
The building blocks are:
● Statements
● State
● Control flow
● Functions
Statement is a single action in a computer.
In a computer statements might include some of the following actions
● input data-information given to the program
● process data-perform operation on a given input
● output data-processed result
State:
Transition from one process to another process under specified condition with
in a time is called state.
1.6 Problem Solving and Python Programming
Control flow:
The process of executing the individual statements in a given order is called
control [Link] control can be executed in three ways
1. sequence
2. selection
3. iteration
It has been proven that any algorithm can be constructed from just three basic
building blocks. These three building blocks are Sequence, Selection, and Iteration
(Repetition).
Sequence
This describes a sequence of actions that a program carries out one after another,
[Link] a list of statements in order. Consider an example,
Example 1.1 Algorithm for Baking Bread
Step1: Add flour.
Step 2: Add salt.
Step 3: Add yeast.
Step 4: Mix.
Step 5: Add water.
Step 6: Knead.
Step 7: Let rise.
Step 8: Bake.
Bread has been baked successfully.
Example 1.2 Algorithm for Addition of two numbers:

Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: Set c = a+b
Step 4: Print c
Step 5: Stop.
Algorithmic Problem Solving 1.7

Example 1.3 Algorithm to prepare Green Tea


Step 1: Fill the kettle with water
Step 2: Boil the water in kettle
Step 3: Put the green tea leaves in the pot
Step 4: Pour the boiling water in the pot
Step 5: Steep the tea leaves for 2 – 3 minutes
Step 6: Stop
Example 1.4 Algorithm to multiply two numbers
Step 1: Input first number as A
Step 2: Input second number as B
Step 3: Set Mul = A*B
Step 4: Print Mul
Step 5: End
Example 1.5 Algorithm for interchanging of two numbers
Step 1 : Start
Start 2 : READ num1, num2
Start 3 : temp = num1
Start 4 : num1 = num2
Start 5 : num2 = temp
Start 6 : PRINT num1, num2
Start 7 : Stop
Selection
Control flow statements are able to make decisions based on the conditions.
Selection is the program construct that allows a program to choose between
different actions. Choose at most one action from several alternative conditions.
1.8 Problem Solving and Python Programming

Condition

Action 1 Action 2

Algorithm for path chooser


Step 1: Check for the destination located from current position.
Step 2:If it is located in right then choose right way
Step 3:If it is located in left then choose left way.
Step 4:Else comeback and search for new way.

Path has been chosen successfully.

The decision statements are:


● if
● if/else
● switch
Algorithmic Problem Solving 1.9

The general form of the if construct can be:


IF condition then process
Although a program might seem like a linear path—one statement following
another— conditional statements act like intersections, allowing you to change
directions on the basis of a given condition.
A condition flow can also be stated in the following manner:
IFcondition
then process 1
ELSE
process 2
This form is known as the if – else construct. Here, if the condition is true then
process 1 is
executed, else process 2 is executed.
Example 1.6 Algorithm for printing Grade
Marks Grade
Above 75 O
60-75 A
50-60 B
40-50 C
Less than 40 D

Step 1 : Enter the marks obtained as M


Step 2 : IF M > 75
Print “O”
Step 3 : IF M>=60 and M<75
Print “A”
Step 4 : IF M>50 and M<60
Print “B”
1.10 Problem Solving and Python Programming
Step 5 : IF M>=40 and M<50
Print “C”
ELSE
Print “D”
[END of IF]
Step 6 : End
Example 1.7 Algorithm to find the equality of two numbers
Step 1 : Start
Step 2 : Input first number as A
Step 3 : Input second number as B
Step 4 : IF A==B
Print “Equal”
ELSE
Print “ Not Equal”
Strep 5 : Stop
Example 1.8 Algorithm to find the largest of three numbers
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Algorithmic Problem Solving 1.11

Example 1.9 Algorithm to find biggest among 2 nos:


Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: If a is greater than b then
Step 4: Print a is big
Step 5: else
Step 6: Print b is big
Step 7: Stop

Repetition
While Statement:
The WHILE construct is used to specify a loop with a test at the top. The beginning
and ending of the loop are indicated by two keywords WHILE and ENDWHILE.
The general form is:
WHILE condition
Sequence
END WHILE
FOR loop:
This loop is a specialized construct for iterating a specific number of times,
often called a “counting” loop. Two keywords, FOR and ENDFOR are used.
The general form is:
FOR iteration bounds
Sequence
END FOR
Repetition (loop) may be defined as a smaller program the can be executed several
times in a main program. Repeat a block of statements while a condition is true.
Example 1.10 Algorithm for Washing Dishes
Step1: Stack dishes by sink.
Step 2: Fill sink with hot soapy water.
Step 3: While moreDishes
1.12 Problem Solving and Python Programming
Step 4: Get dish from counter,Wash dish
Step 5: Put dish in drain rack.
Step 6: End While
Step 7: Wipe off counter.
Step 8: Rinse out sink.
Example 1.11 Algorithm to calculate factorial no:
Step1: Start
Step 2: Read the number num.
Step 3: Initialize i is equal to 1 and fact is equal to 1
Step 4: Repeat step4 through 6 until I is equal to num
Step 5: fact = fact * i
Step 6: i = i+1
Step 7: Print fact
Step 8: Stop
Example 1.12 Algorithm to find the factorial of a number
Step 1. Read the value of n.
Step 2. i = 1 , F =1
Step 3. if ( i > n ) go to 7
Step 4. F = F * i
Step 5. i = i + 1
Step 6. go to 3
Step 7. Display the value of S
Step 8. Stop
Example 1.13 Algorithm to print numbers from 1 to 10
Step 1: Set i=1, n=10
Step 2: Repeat steps 3 and 4 while i<=n
Step 3: Print i
Step 4: Set i=i+1
[End of loop]
Step 5: End
Algorithmic Problem Solving 1.13

Recursion
Recursion is a technique of solving a problem by breaking it down into smaller
and smaller sub problems until you get to a small enough problem that it can be easily
solved. Usually, recursion involves a function calling itself until a specified a specified
condition is met.
Example 1.14 Algorithm for factorial using recursion
Step 1 : Start
Step 2 : Input number as n
Step 3 : Call factorial(n)
Step 4 : End

Factorial(n)
Step 1 : Set f=1
Step 2: IF n==1 then return 1
ELSE
Set f=n*factorial(n-1)
Step 3 : print f

Suggested Link to refer:


[Link]
Functions:
Functions allow us to conceive of our program as a bunch of sub-steps. When
any program seems too hard, just break the overall program into sub-steps! They allow
us to reuse code instead of rewriting it. Every programming language lets you create
blocks of code that, when called, perform tasks. All programming functions have input
and output. The function contains instructions used to create the output from its input.
The general form of a function definition has return type, parameter list, function
name and function body.
def function_name( parameter list ):
body of the function
return [expression]
1.14 Problem Solving and Python Programming
1.3 ALGORITHM NOTATIONS (EXPRESSING ALGORITHMS)
As we know that, an algorithm is a sequence of finite instructions, often used for
calculation and data processing.
Input List

Algorithm

A step-by-step method for


solving a problem or doing a task

Output List

Algorithms can be expressed in many kinds of notation, including

1.3.1 Pseudocode
Pseudo code consists of short, readable and formally styled English languages
used for explain an algorithm.
● It does not include details like variable declaration, subroutines.
● It is easier to understand for the programmer or non programmer to
understand the general working of the program, because it is not based on
any programming language.
● It gives us the sketch of the program before actual coding.
● It is not a machine readable
● Pseudo code can’t be compiled and executed.
Algorithmic Problem Solving 1.15

● There is no standard syntax for pseudo code.

[Link] Guidelines for writing pseudo code


● Write one statement per line
● Capitalize initial keyword
● Indent to hierarchy
● End multiline structure
● Keep statements language independent

[Link] Common keywords used in pseudo code


The following gives common keywords used in pseudo codes.
1. This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given
expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and
initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested
automatically.

[Link] How to write a pseudo code


Start by writing down the purpose of the process.
Write initial steps of pseudo code that set the stage for functions.
Write functional pseudo code.
Add comments, if necessary.
Read over the finished project for logic errors .
Review the pseudo code.
1.16 Problem Solving and Python Programming
Advantages:
● Pseudo is independent of any language; it can be used by most programmers.
● It is easy to translate pseudo code into a programming language.
● It can be easily modified as compared to flowchart.
● Converting a pseudo code to programming language is very easy as
compared with converting a flowchart to programming language.
Disadvantages:
● It does not provide visual representation of the program’s logic.
● There are no accepted standards for writing pseudo codes.
● It cannot be compiled nor executed.
● For a beginner, It is more difficult to follow the logic or write pseudo code
as compared to flowchart.
Syntax for if else: Example: Greates of two numbers
IF (condition)THEN BEGIN
statement READ a,b
.... IF (a>b) THEN
DISPLAY a is greater
ELSE
ELSE
statement
DISPLAY b is greater
.... END IF
ENDIF END
Syntax for For: Example: Print n natural numbers
FOR (start-value to end-value)DO BEGIN
statement GET n
.... INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
BEGIN
WHILE (condition) DO GET n
statement INITIALIZE i=1
... WHILE (i<=n) DO
PRINT i
ENDWHILE i=i+1
ENDWHILE
END
Algorithmic Problem Solving 1.17

pseudo code is made up of the following logic structure,


● Sequential logic
● Selection logic
● Iteration logic
Sequence Logic
● It is used to perform instructions in a sequence,that is one after another
● Thus,for sequence logic ,pseudocode instructions are written in an order in
which they are to be performed.
● The logic flow of pseudocode is from top to bottom.
Example 1.15 Pseudo code to add two numbers:
START
READ a,b
COMPUTE c by adding a &b
PRINT c
STOP

Selection Logic
● It is used for making decisions and for selecting the proper path out of two
or more alternative paths in program logic.
● It is also known as decision logic.
● Selection logic is depicted as either an IF..THEN or an IF…THEN..ELSE
Structure.
Example 1.16 Pseudocode to Find Biggest of two numbers:
START
READ a and b
IF a>b THEN
PRINT “A is big”
ELSE
PRINT “B is big”
ENDIF
STOP
1.18 Problem Solving and Python Programming
Repetition Logic
● It is used to produce loops when one or more instructions may be executed
several times depending on some conditions.
● It uses structures called DO_WHILE,FOR and REPEAT UNTIL
Example 1.17 Pseudocode to print first 10 natural numbers
START
INITIALIZE a?0
WHILE a<10
PRINT a
ENDWHILE
STOP
Suggested Link to refer :
[Link]

1.3.2 Flowchart
A flowchart is a visual representation of the sequence of steps and decision needed
to perform a process.
Flow chart is defined as graphical representation of the logic for problem solving.
The purpose of flowchart is making the logic of the program clear in a visual
representation.
Flowchart symbols
Here are some of the common flowchart symbols.
Name Symbol Use in flowchart

Oval Denotes the beginning or end of a program.

Flow line Denotes the direction of logic flow in a


program.

Parallelogram Denotes either an input operation (e.g.,


INPUT) or an output operation (e.g.
PRINT)
Algorithmic Problem Solving 1.19

Rectangle Denotes a proces sto be carried out (e.g.,


an addition)

Diamond Denotes a decision (or branch) to be made.


The program should continue along one of
two routes (e.g, [Link]/ELSE)
Suggested Links : (Flowchart Symbols)
[Link]
Rules for drawing a flowchart
1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.

NO
YES

5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.


7. Intersection of flow lines should be avoided.
1.20 Problem Solving and Python Programming
Advantages of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a
system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
3. Proper documentation: - Program flowcharts serve as a good program
documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put efforts
more efficiently on that part.
Disadvantages of flow chart:
1. Complex logic: - Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
4. Cost: For large application the time and cost of flowchart drawing becomes
costly.
Flowchart is made up of the following logic structure,
● Sequential logic
● Selection logic
● Iteration logic
Sequence Logic
In a computer program or an algorithm, sequence involves simple steps which
are to be executed one after the other. The steps are executed in the same order in
which they are written.
Algorithmic Problem Solving 1.21

Below is an example set of instructions to add two numbers and display the
answer.

BEGIN ADD Two Numbers

END Add Two Numbers

Selection Logic
Selection is used in a computer program or algorithm to determine which
particular step or set of steps is to be executed. This is also referred to as a ‘decision’.
A selection statement can be used to choose a specific path dependent on a
condition.
There are two types of selection:
● binary selection (two possible pathways)
● multi-way selection (many possible pathways)
Following is the example flowchart to find biggest among two numbers
Start

Read A, B

Yes No
Is A > B

Print B
Print A

End
1.22 Problem Solving and Python Programming
Example 1.18 Flow chart for biggest of three numbers

Print Print Print


‘B is the ‘C is the ‘A is the
largest number largest number largest number

Example 1.19 Flow chart for sum of N Natural numbers

Read N

Sum = sum + n

Display Sum
Algorithmic Problem Solving 1.23

Example 1.20 Roots of a quadratic equation ax2+bx+c=0

Calculate discriminant

ip -b/2a
rp -(D)/2a

Display r1 and r2

Repetition Logic
Repetition allows for a portion of an algorithm or computer program to be
executed any number of times dependent on some condition being met.
An occurrence of repetition is usually known as a loop.
The termination condition can be checked or tested at the beginning or end of
the loop, and is known as a pre-test or post-test, respectively.
Iteration & Recursion
Iteration and recursion are key Computer Science techniques used in creating
algorithms and developing software.
1.24 Problem Solving and Python Programming
In simple terms, an iterative function is one that loops to repeat some part of the
code, and a recursive function is one that calls itself again to repeat the code.
Example 1.21 Flowchart to find factorial of given no
START

Fact 1, Num 0

Read Num

No
IS Num
> 1? Print Fact

Yes Stop

Fact Fact * Num

Num Num-1

pre-test loop post-test


Algorithmic Problem Solving 1.25

1.3.3 Representation of Algorithm using Programming Language


● Algorithms describe the solution to a problem in terms of the data needed to
represent the problem instance and the set of steps necessary to produce the
intended result.
● Programming languages must provide a notational way to represent both the
process and the data.
● To this end, languages provide control constructs and data types.
Programming is the process of taking an algorithm and encoding it into a notation,
a programming language, so that it can be executed by a computer.
Although many programming languages and many different types of computers
exist, the important first step is the need to have the solution.
Without an algorithm there can be no program.
● Control constructs allow algorithmic steps to be represented in a convenient
yet unambiguous way.
● At a minimum, algorithms require constructs that perform sequential
processing, selection for decision-making, and iteration for repetitive control.
● As long as the language provides these basic statements, it can be used for
algorithm representation.
Simply we can say programming as like below
Programming is implementing the already solved problem (algorithm)
in a specific computer language where syntax and other relevant
parameters are different, based on different programming languages.

Computer Languages

Low Level Language Middle Level Language High Level Language


(Machine Language) (Assembly Language)
Use 1’s & 0’s to Use mnemonics to Similar to
create instructions create instructions human language
Ex: Binary Language COBOL, FORTRAN, BASIC
Assembly Language
C, C++, JAV
1.26 Problem Solving and Python Programming
Low level Language(Machine level Language)
A low-level language is a programming language that deals with a computer’s
hardware components and constraints.
In simple we can say that ,low level language can only be understand by computer
processor and components.
Middle level Language(Intermediate Language)
Medium-level language serves as the bridge between the raw hardware and
programming layer of a computer system.
Medium-level language is also known as intermediate programming language
and pseudo language.
C intermediate language and Java byte code are some examples of medium-
level language.
High level Language (Human understandable Language)
A high-level language is any programming language that enables development
of a program in a much more user-friendly programming context.
High-level languages are designed to be used by the human operator or the
programmer.
They are referred to as “closer to humans.” In other words, their programming
style and context is easier to learn and implement than low-level languages
BASIC, C/C++ and Java are popular examples of high-level languages.

1.4 ALGORITHMIC PROBLEM SOLVING


“Algorithmic-problem solving”; this means solving problems that require the
formulation of an algorithm for their solution.
The formulation of algorithms has always been an important element of problem-
solving.
Why we need to go for algorithm to solve problem?
● A computer is a tool that can be used to implement a plan for solving a
problem.
● A computer program is a set of instructions for a computer. These instructions
describe the steps that the computer must follow to implement a plan.
Algorithmic Problem Solving 1.27

● An algorithm is a plan for solving a problem.


● A person must design an algorithm.
● A person must translate an algorithm into a computer program.
An algorithmic Development Process
Every problem solution starts with a plan. That plan is called an algorithm.
An algorithm is a plan for solving a problem.
There are many ways to write an algorithm.
● Some are very informal.
● some are quite formal.
● mathematical in nature.
● some are quite graphical.
Once we have an algorithm, we can translate it into a computer program in some
programming language. Our algorithm development process consists of five major
steps.

Step 1: Obtain a description of the problem.


Step 2: Analyze the problem.
Step 3: Develop a high-level algorithm.
Step 4: Refine the algorithm by adding more detail.
Step 5: Review the algorithm.

1. Understanding the Problem


● It is the process of finding the input of the problem that the algorithm solves.
● It is very important to specify exactly the set of inputs the algorithm needs
to handle.
● A correct algorithm is not one that works most of the time, but one that
works correctly for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device
1.28 Problem Solving and Python Programming
● If the instructions are executed one after another, it is called sequential
algorithm.
● If the instructions are executed concurrently, it is called parallel algorithm.

Understand the problem

computational means,
exact vs. approximate solving,

Design an algorithm

Prove correctness

Analyze the algorithm

Code the algorithm

Choosing between Exact and Approximate Problem Solving


● The next principal decision is to choose between solving the problem exactly
or solving it approximately.
● Based on this, the algorithms are classified as exact algorithm and
approximation algorithm.
Algorithmic Problem Solving 1.29

2. Deciding a data structure:

● Data structure plays a vital role in designing and analysis the algorithms.

● Some of the algorithm design techniques also depend on the structuring


data specifying a problem’s instance

● Algorithm+ Data structure=programs.

Algorithm Design Techniques

● An algorithm design technique (or “strategy” or “paradigm”) is a general


approach to solving problems algorithmically that is applicable to a variety
of proble ms from different areas of computing.

● Learning these techniques is of utmost importance for the following reasons.

● First, they provide guidance for designing algorithms for new problems,

● Second, algorithms are the cornerstone of computer science

Methods of Specifying an Algorithm

● Pseudocode is a mixture of a natural language and programming language-


like constructs. Pseudocode is usually more precise than natural language,
and its usage often yields more succinct algorithm descriptions.

● In the earlier days of computing, the dominant vehicle for specifying


algorithms was a flowchart, a method of expressing an algorithm by a
collection of connected geometric shapes containing descriptions of the
algorithm’s steps.

● Programming language can be fed into an electronic computer directly.


Instead, it needs to be converted into a computer program written in a
particular computer language. We can look at such a program as yet another
way of specifying the algorithm, although it is preferable to consider it as
the algorithm’s implementation.

3. Proving an Algorithm’s Correctness

● Once an algorithm has been specified, you have to prove its correctness.
That is, you have to prove that the algorithm yields a required result for
every legitimate input in a finite amount of time.
1.30 Problem Solving and Python Programming
● A common technique for proving correctness is to use mathematical
induction because an algorithm’s iterations provide a natural sequence of
steps needed for such proofs.
● It might be worth mentioning that although tracing the algorithm’s
performance for a few specific inputs can be a very worthwhile activity, it
cannot prove the algorithm’s correctness conclusively. But in order to show
that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.
4. Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs, Space efficiency,
indicating how much extra memory it uses.
2. Simplicity.
● An algorithm should be precisely defined and investigated with
mathematical expressions.
● Simpler algorithms are easier to understand and easier to program.
● Simple algorithms usually contain fewer bugs.
5. Coding an Algorithm
● Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorithm presents both a peril and an
opportunity.
● A working program provides an additional opportunity in allowing an
empirical analysis of the underlying algorithm. Such an analysis is based on
timing the program on several inputs and then analysing the results obtained.

1.5 SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS


1. Iterations
2. Recursions
Iterations:
A sequence of statements is executed until a specified condition is true is called
iterations.
Algorithmic Problem Solving 1.31

1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
FOR (start-value to end-value)DO BEGIN
statement GET n
.... INITIALIZE i=1
ENDFOR FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
GET n
statement
INITIALIZE i=1
... WHILE (i<=n) DO
ENDWHILE PRINT i
i=i+1
ENDWHILE
END

print i
1.32 Problem Solving and Python Programming
Recursions:
● A function that calls itself is known as recursion.
● Recursion is a process by which a function calls itself repeatedly until some
specified condition has been satisfied.
Example 1.22 Algorithm for factorial of n numbers using recursion:
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact

if(n = 1)
call factorial(n)

fact = n*factorial(n-1) return fact


Print fact
Algorithmic Problem Solving 1.33

Example 1.23 Pseudo code for factorial using recursion:

Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
Sub function factorial(n):
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

1.6 EXAMPLE ALGORITHMS (ILLUSTRATIVE PROBLEMS)

1.6.1 Find minimum in a list


Problem: Given a list of positive numbers, return the smallest number on the
list.
Inputs: A list L of positive numbers. This list must contain at least one number.
(Asking for the smallest number in a list of no numbers is not a meaningful question.)
Outputs: A number n, which will be the smallest number of the list.
Algorithm:
Start
Get positive numbers from user and add it in to the List L
Set min to L[0].
For each number x in the list L, compare it to min. If x is smaller, set min to x.
min is now set to the minimum number in the list.
Stop

You might also like