Py Unit 1
Py Unit 1
Illustrative problems: find minimum in a list, insert a card in a list of sorted cards, and guess an integer
number in a range, Towers of Hanoi.
Resource Sharing:
In the initial stages of development, computers used to be isolated machines.
With the tremendous growth in computer technologies, computers today have the capability to connect
with each other.
Apart from device sharing, data and information can also be shared among groups of computers, thus
creating a large information and knowledge base.
In second generation computers, magnetic cores were used as primary memory and magnetic disks as
secondary storage devices. However, they still relied on punched cards for input and printouts for
output.
One of the major developments of this generation includes the progress from machine language to
assembly language.
Assembly language used mnemonics (abbreviations) for instructions rather than numbers, for
example, ADD for addition and MULT for multiplication.
Examples: PDP-8, IBM 1401 and IBM 7090.
Figure: Transistors
Figure: IC
Figure: Microprocessor
Fifth generation computers will use mega chips, which will result in the production of microprocessors
having millions of electronic components on a single chip.
They will use intelligent programming (AI) and knowledge-based problem-solving techniques.
Computers can be classified according to their purpose (whether the computer is meant for general-
purpose or special-purpose), data handling (whether the computer uses analog or digital data or
combination of both), and functionality (whether the computer handles large volume of data or small).
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
A computer can be viewed as a system, which consists of a number of interrelated components that
work together with the aim of converting data into information.
To attain information, data is entered through input unit, processed by central processing unit (CPU),
and displayed through output unit.
In addition, computers require memory to process data and store output.
All these parts (the central processing unit, input, output, and memory unit) are referred to
as hardware of the computer.
Components of a computer
The basic components of a computer system include input unit, central processing unit (CPU),
output unit, and storage unit.
The input unit is formed by attaching various input devices such as keyboard, mouse, light pen, and so
on to a computer. An input device is an electromechanical device that accepts instructions and data
from the user.
Some of the commonly used input devices are keyboard, pointing devices like mouse and joystick,
digital camera, and scanners.
The central processing unit (CPU) referred to as the “brain” of a computer system, converts data
(input) into meaningful information (output). A CPU controls all internal and external devices,
performs arithmetic and logic operations, and operates only on binary data, that is, data composed of 1s
and 0s.
The arithmetic/logic unit (ALU) contains the electronic circuitry that executes all arithmetic and
logical operations on the data made available to it.
The control unit of the CPU contains circuitry that uses electrical signals to direct the entire computer
system to carry out, or execute, stored program instructions. This unit checks the correctness of
sequence of operations.
Registers are special-purpose, high-speed temporary memory units that hold various types of
information such as data, instructions, addresses, and the intermediate results of calculations.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
The output unit is formed by attaching output devices such as printer, monitor, and plotter to the
computer. An output device is used to present the processed data (results) to the user.
A computer system incorporates storage unit to store the input entered through input unit before
processing starts and to store the results produced by the computer before supplying them to the output
unit.
The output, which can be easily understood and used by human beings, are of two forms: hard copy
and soft copy.
Based on the hard copy and soft copy outputs, the output devices are classified into: hard copy and
soft copy output devices. Printers and plotters are the most commonly used hard copy output devices.
The commonly used soft copy output is computer monitor.
Memory classified into two broad categories: primary memory and secondary memory.
Primary Memory, also known as main memory, stores data and instructions for processing and can be
further classified into random access memory (RAM) and read only memory (ROM).
Secondary Memory, also known as auxiliary memory or external memory is used for storing
instructions (software programs) and data, since main memory is temporary and limited in size.
Applications:
Science
Education
Medical and Health Care
Engineering/Architecture/Manufacturing
Entertainment
Communication
Business Application
Publishing
Banking
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of
solutions.
The problem solving process starts with the problem specifications and ends with a correct
program.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Problem solving technique is a set of techniques that helps in providing logic for solving a problem.
Problem solving can be expressed in the form of
Algorithms
Flowcharts.
Pseudo codes.
Programs
Analysis - In this stage we should find what the problem should do.
Design - The way or method of how our problem is solved.
Development - The method found in design is then coded here in a given programming language.
Testing -Here we verify that the program written is working correctly.
Implementation – Finally the program is ready to use.
Algorithm
It is defined as a sequence of instructions that describe a method for solving a problem.
In other words it is a step by step procedure for solving a problem.
Should be written in simple English.
Each and every instruction should be precise and unambiguous.
Instructions in an algorithm should not be repeated infinitely.
Algorithm should conclude after a finite number of steps.
Should have an end point.
Derived results should be obtained only after the algorithm terminates.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
States
An algorithm is deterministic automation for accomplishing a goal which, given an initial state, will
terminate in a defined end-state.
An algorithm will definitely have start state and end state.
Control Flow
Control flow which is also stated as flow of control, determines what section of code is to run in
program at a given time.
There are three types of flows, they are
Sequential control flow
Selection or Conditional control flow
Looping or repetition control flow
Example
Description: To find the sum of two numbers.
Step 1: Start
Step 2: Read the value of ‘a’
Step 3: Read the value of ‘b’
Step 4: Calculate sum=a+b
Step 5: Print the sum of two number
Step 6: Stop
Basic structure:
Example
Description: finding the greater number
Step 1: Start
Step 2: Read a
Step 3: Read b
Step 4: if a>b then
print a is greater
Step 5: else
print b is greater
Step 6: Stop
Basic Structure:
Repetition control flow means that one or more steps are performed repeatedly until some condition is
reached.
This logic is used for producing loops in program logic when one or more instructions may need to be
executed several times or depending on condition.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example:
Description: to print the values from 1 to n
Step 1: Start
Step 2: Read the value of ‘n’
Step 3: Initialize i as 1
Step 4: Repeat step 4.1 until i< n
Step 5: Print i
Step 6: Stop
Function
A function is a block of organized, reusable code that is used to perform a single, related action.
Function is also named as methods, sub-routines.
Elements of functions:
Name for declaration of function.
Body consisting local declaration and statements.
Formal parameter.
Optional result type.
Basic Syntax
function_name(parameters)
function statement1
…………………...
……………………
function n statements
function_name(parameters)
end function
Algorithm for addition of two numbers using function
main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
1. Pseudocode
Pseudocode is an informal high-level description of the operating principle of a computer
program or algorithm.
It uses the basic structure of a normal programming language, but is intended for human reading
rather than machine reading.
It is text based detail design tool. Pseudo means false and code refers to instructions written in
programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules.
The pseudocode is written in normal English language which cannot be understood by the computer.
Example:
Pseudocode: To find sum of two numbers
READ num1, num2
sum=num1+num2
PRINT sum
Example:
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b is greater
ENDIF
Advantages of Pseudocode
Can be done easily on a word processor
Easily modified
Implements structured concepts well
It can be written easily
It can be read and understood easily
Converting pseudocode to programming language is easy as compared with flowchart.
Disadvantages of Pseudocode
It is not visual
There is no standardized style or format
2. Flowchart
A graphical representation of an algorithm.
Flowcharts is a diagram made up of boxes, diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.
Only one flow line should enter a decision symbol, but two or three flow lines, one for each
possible answer, cap leave the decision symbol.
If flowchart becomes complex, it is better to use connector symbols to reduce the number of
flow lines.
Ensure that flowchart has logical start and stop.
Advantages of Flowchart
Communication: Flowcharts are better way of communicating the logic of the system.
Effective Analysis With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation: Flowcharts are used for good program documentation, which is needed for
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
various purposes.
Efficient Coding: The flowcharts act as a guide or blue print during the system analysis and program
development phase.
Systematic Testing and Debugging: The flowchart helps in testing and debugging the program
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 Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart
becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re- drawing
completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes problematic.
Sequence Structure
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Conditional Structure
Conditional structure is used to check the condition. It will be having two outputs only (True or False)
IF and IF…ELSE are the conditional structures used in Python language.
CASE is the structure used to select multi way selection control. It is not supported in Python.
IF
IF… ELSE
IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1, else,
that is condition is false then execute Process2
Yes
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example:
Programming Language
A programming language is a vocabulary and set of grammatical rules for instructing a computer or
computing device to perform specific tasks.
In other word it is set of instructions for the computer to solve the problem.
Programming Language is a formal language with set of instruction, to the computer to solve a
problem.
The program will accept the data to perform computation.
Program= Algorithm +Data Need for Programming Languages
Programming languages are also used to organize the computation.
Using Programming language we can solve different problems.
To improve the efficiency of the programs.
Algorithmic problem solving is solving problem that require the formulation of an algorithm for the
solution.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Coding an algorithm
Programming the algorithm by using some programming language.
Validity is done through testing and debugging.
Inputs should fall within a range and hence require no verification. The analysis has to be done in various
sets of inputs.
A good algorithm is a result of repeated effort and work.
The program's stopping or terminating condition has to be set.
Another important issue is the question of whether or not every problem can be solved by an algorithm.
And the last, is to avoid the ambiguity which arises for a complicated algorithm.
Iteration
The iteration is when a loop repeatedly executes till the controlling condition becomes false.
The iteration is applied to the set of instructions which we want to get repeatedly executed.
Iteration includes initialization, condition, and execution of statement within loop and update
(increments and decrements) the control variable.
A sequence of statements is executed until a specified condition is true is called iterations.
for loop
while loop
GE3151-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.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
o In recursive algorithm, the function calls itself until the condition is met.
o It is slower than iteration.
o It uses more memory than iteration.
o Recursion is like a selection structure, and which makes code smaller and clean.
o Tracing the code will be more difficult in the case large programs.
Iterative algorithm:
ILLUSTRATIVE PROBLEMS
1. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare n, guess
Step 3: Compute
guess=input
Step 4: Read guess
Step 5: If guess>n, then
Print your guess is too high
Else
Step6:If guess<n, then
Print your guess is too low
Else
Step 7:If guess==n,then
Print Good job
Else
Nope
Step 8: Stop
Pseudocode:
BEGIN
COMPUTE guess=input
READ guess,
IF guess>n
PRINT Guess is high
ELSE
IF guess<n
PRINT Guess is low
ELSE
IF guess=n
PRINT Good job
ELSE
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Nope
END
Flowchart
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Read item
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
Step 11: Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Flowchart:
4. Towers of hanoi
This problem was introduced by French mathematician Edouard lucas in 1883.
Problem:
Given 3 posts labeled as A, B, and C. Now, in post A, there are n disk of different sizes arranged in
the order of largest disk at the bottom, smallest disk on the top. Post B and C are empty.
The objective is to move the n disks from post A to post C, obeying the following rules:
Rule 1: Only one disk can be moved from one post to another post at a time.
Rule 2: A disk can be placed only on a top of a larger disk
Rule 3: A disk can be moved from top only
Rule 4: No disk can be placed on top of smaller disk.
Post A is known as Source
Post B is known as Auxiliary
Post C is known as Destination
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
If n = 2 Move disk 1 A to B
Move disk 2 A to C
Move disk 1 B to C
If n = 3
Initial Condition
Step 1: Move disk 1 from post A to C
Step 2: Move disk 2 from post A to B
Step 3: Move disk 1 from post C to B
Step 4:Move disk 3 from post A to C
Step 5: Move disk 1 from post B to A
Step 6: Move disk 2 from post B to C
Step 7: Move disk 1 from post A to C
If n=4
Initial condition:
Step 1: Move disk 1 from post A to B
Step 2: Move disk 2 from post A to C
Step 3: Move disk 1 from post B to C
Step 4: Move disk 3 from post A to B
Step 5: Move disk 1 from C to A
Step 6: Move disk 2 from post C to B
Step 7; Move disk 1 from post A to B
Step 8: Move disk 4 from post A to C
Step 9: Move disk 1 from post B to C
Step 10: Move disk 2 from post B to A
Step 11: Move disk 1 from post C to A
Step 12: Move disk 3 from post B to C
Step 13:Move disk 1 from post A to B
Step 14:Move disk 2 from post A to C
Step 15:Move disk 1 from post B to C
Stop
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
2 MARKS
1. What is an algorithm?
a. Algorithm is a set of rules for solving a problem in finite number of steps.
b. An algorithm defined as a finite sequence of explicit instructions.
c. Algorithm can have steps that repeat (iterate) or require decisions (logic and comparison) until
the task is completed.
2. Write an algorithm two accept two numbers compute the sum and print the result.
Step 1: Start
Step 2: Read two values in ‘A’ and ‘B’
Step 3: Add ‘A’ and ‘B’ and store the result in ‘C’
Step 4: Display ‘C’
Step 5: Stop
Step 3: Stop
8. Define Function.
Function is self contained block.
It is used to perform specific task
Larger programs are subdivided into smaller one by the use of functions (Modular
programming)
Functions are also named as methods, subroutines or procedures.
B=min(A)
print(B)
PART B
Program:
list=[1,2,4,9,13]
n=10
for i in range(len(list)):
if(list[i]>n):
index=i
break
list=list[:i]+[n]+list[i:]
print(list)
10. Draw a flowchart to accept three distinct numbers find the greatest and print the result.
38
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
39
1. Write a program to find the area and circumference of the circle.
Algorithm:
Step 1: Start
Step 2: Input the radius of the circle.
Step 3: Find the area and circumference of the circle using the formula
Area 3.14*r*r
Circumference 2 * 3.14 *r
Step 4: Print the area and circumference of the circle
Step 5: Stop
Pseudocode:
Set initial zero to Area, Circumference
READ the radius of the circle
Find the area and circumference of the circle using formula
Area = 3.14 * r*r
Circumference = 2*3.14*r
WRITE output of area and circumference of the circle
Stop
Flow Chart
Start
Read r
Stop 14
2. Write a program to find the roots of the quadratic equation.
Algorithm:
Step 1: Start
Step 2: Enter the value of a,b ,c
Step 3: Find the value of ‘D’ of using the formula
D b * b - 4*a*c
Step 4: If D is greater than or equal to zero then find the two roots are
root 1 (-b+sqrt(d))/(2*a)
root 2 (-b-sqrt(d))/(2*a)
Step 5: Print the two roots, root1,root2
Step 6: If D is not greater than or equal to zero, then print the roots are imaginary.
Step 7: Stop Flow Chart:
Pseudocode:
Start
Set initial zero to root1,root2
READ the value of a,b,c
Read a,b,c
Find descriminant
D b*b – 4*a*c
IF D>=0 THEN D=b*b – 4*a*c
Print root 1,
root 2
15 Stop
3. Write a program to find the factorial of the given number.
Algorithm:
Step 1: Start
Step 2: Read the value of n
Step 3: Set initial values to Fact i 1
Step 4: is i < = n else Goto step 6
Step 4.1 : Fact Fact * i
Step 4.2 : i i+1
Step 5: Goto Step 4
Step 6 : Print Fact
Step 7 : Stop
No
If i<
=n
Yes
i=i+1
Stop
16
4. Write a program to find the given number is an Armstrong number or not.
Algorithm:
Step 1: Start
Step 2: Enter the value of n
Step 3: Assign a n, r = 0, sum =0
Step 4: If n > 0 ELSE Goto Step 6
Step 4.1 : r n mod 10
Step 4.2 : sum sum + r * r * r
Step 4.3 : n n div 10
Step 5: Goto Step 4
Step 6: IF a == sum THEN print Armstrong
ELSE print not Armstrong
Step 7: Stop
Pseudocode:
ELSE
WRITE the result is not Armstrong
ENDIF
Stop
17
FlowChart
Start
Read n
a=n
Sum=0
No
is
n>0
Yes
r= n mod 10
Sum = Sum + r *
r*r
n = n div 10
if No
a=
Sum
Yes
Print not
Print
Armstrong
Armstrong
Stop
18
5. Write a program to find whether the number is prime or not.
Step 1: Start
Step 2: Assign i 2 Start
Step 3: READ n
Step 4: REPEAT Steps 4.1, 4.2
i =2
UNTIL i < = n-1
Step 4.1 : IF (n mod i =0) THEN
Read n
Step 4.1.1: Prime not Prime
Step 4.1.2: Exit
Step 4.2 : i i+1
Step 5: IF (i=n) Then if No
i<=n
Step 6: Print Prime
Step 7: Stop Yes
Pseudocode:
if
Set initial 2 to i n % i ==0
READ n
IF (i<=n-1)
IF (n mod i=0)
Prime not Prime
WRITE “ Not Prime “
EXIT
ENDIF A
i = i+1
IF (i =n)
i=i+1
WRITE “Prime”
ENDIF
ENDIF
Stop if = n
No
Yes
19
6. Write a program to find the largest of three numbers.
Step 1: Start
Step 2: READ a,b,c Start
Step 3: IF (a>b) and (a>c ) Then
Step 3.1 : Print ‘A is Big’
ELSE
Read a,b,c
Step 4: IF (b>c) Then
Step 4.1 : Print ‘B is big’
ELSE Yes
Step 4.2: Print ‘C is Big’ if a>b and a >c
Step 5: Stop
No Print A is
Big
Pseudocode: Yes
if b > c
READ the value for a,b ,c Print B is
IF (a>b and a>c ) THEN No big
WRITE ‘A is Big ’
Print C is Big
ELSE IF ( b > c) THEN
WRITE ‘ B is Big ’
ELSE
WRITE ‘ C is Big’ Stop
ENDIF
Stop
𝑥3 𝑥5 𝑥7 𝑥𝑛
7. Write a program to solve the series s =x - + + +
3! 5! 7! 𝑛!
Algorithm:
Step 1: Start
Step 2: Read the value of x,n
Step 3: Assign s 0 , term x, i 1
Step 4: The value of the term incremented to get next term and the term is added to s.
20
Step 5: s s+ term
Step 6: term = term * x* x(-1) / (i+1) (i +2)
Step 7: i i+2
Step 8: Repeat step 5 to step 7 WHILE (i <=n)
Step 9: Stop
Pseudocode:
Flow Chart :
Start
Read x,n
s =0 term = x i =1
while i < = n
s = s + term
𝑡𝑒𝑟𝑚∗∗(−1)
term = (𝑖+1)(𝑖+2)
i = i +2
Print s
Stop
21
8. Write a program to find minimum and maximum number from the list.
Algorithm:
Pseudocode:
Set initial i
READ n
READ an array a[] of ‘n’ numbers
Set MAX = a[0], MIN = a[0]
FOR i =2 to n
if a[i] > MAX then MAX = a[i]
if a[i] < MIN then MIN = a[i]
end-if
Print MAX, MIN
Stop
22
Flow Chart
Start
Read n
For i = 1 to n
Read a[i]
for i =2 to n
If Yes
Yes
a[i] > Max
Max = a[i]
No
No
Yes
If Yes
a[i] < Min
No Min = a[i]
No
23
Stop
9. Write a program for Insertion Sort
Algorithm:
Pseudocode:
24
Flow Chart:
Start
Read n
n = A[i]
Position = i
while
Position > 0 and
A[Position] > n
No
A[Position] = A[Position-1]
Position = Position -1
Positio Yes
A[Position] = n
Stop
25