UNIT 1 problem solving and python programming
UNIT 1 problem solving and python programming
UNIT 1 problem solving and python programming
23CS101T– SOLVING
Problem SolvingAND PYTHON
and Python PROGRAMMING
Programming
1. FUNDAMENTALS OF COMPUTING
A computer is an electronic device that accepts data from the user, processes it,
produces results, displays them to the users, and stores the results for future usage.
Data is a collection of unorganized facts & figures and does not provide any further
information regarding patterns, context, etc. Hence data means "unstructured facts
and figures".
Information is a structured data i.e. organized meaningful and processed data. To
process the data and convert into information, a computer is used
Computer components are the essential building parts of developing a functional computer
system. The components that make up a computer are called computer components. There
are 5 main computer components that are given below
o Input Devices
o CPU
o Output Devices
o Primary Memory
o Secondary Memory
1
Input devices:
A computer system's input devices are important because they allow users to enter
commands and data. Keyboards, mice, scanners, and microphones are numerous examples
of input devices.
CPU:
A computer machine's "brain" is its central processing unit (CPU). It executes the
calculations and commands required for functioning of the computer device. The CPU
comprises some components: the control unit, the arithmetic logic unit (ALU), and
registers.
o The CPU's control unit is in charge of reading and decoding instructions from
memory. The right part of the CPU receives and executes these instructions from the
control unit.
o The ALU operates addition, subtraction, comparison calculations, and other logical
and mathematical processes.
o Registers are compact, high-speed data and instruction storage spaces within the
CPU.
o The clock speed, measured in GHz (gigahertz), controls what number of commands
the integral processing unit can process in a second.
Primary Memory:
The CPU has direct access to primary memory, sometimes referred to as random access
memory (RAM). The data and instructions that are currently being processed are kept in
primary memory. The data and instructions are accessed by the CPU from primary memory
when a computer programme is running. The information is removed from primary
memory once the programme is completed.
Primary memory is classified into two types: random access memory (RAM) and read-
only memory (ROM).
2
o RAM is the most common form of primary memory and is used to store data and
instructions that the CPU wishes to access frequently. RAM is volatile, which means
that its contents are lost when the computer is turned off. But RAM can be effortlessly
and quickly written to and read from, making it a really perfect storage medium for
temporary data and instructions.
o ROM is a form of memory this is used to store data and instructions that don't
change. ROM is non-volatile, which means that its contents aren't lost while the
computer is turned off. ROM is used to keep firmware and the laptop's basic
input/Output machine (BIOS), that are required for the computer to boot up and
function well.
Secondary Memory:
Secondary memory, also called auxiliary storage, is a type of computer memory that is used
to store data and programs that aren't currently being utilized by the CPU. In contrast to
primary memory, secondary memory is non-volatile, which means that its contents are not
lost when the computer is turned off.
There are several types of secondary memory devices, such as hard disk drives (HDD),
solid-state drives (SSD), optical disks (including CDs and DVDs), and USB flash drives.
Output Devices:
Output devices are hardware components of a computer system that are used to show or
send data from the pc to the user or any other device. They enable customers to view and
engage with the information and applications the computer is processing. Speakers,
projectors, printers, and monitors are a few examples of output devices.
FUNCTIONS OF COMPUTERS
Computer components collaborate to carry out the numerous tasks necessary for a
computer system to run. The following are some of the major operations carried out by
computer components:
1. Inputting: It is the process of entering raw data, instructions and information into
the computer. Keyboards, mice, and scanners are used as input devices to help with
the process. These tools are used to enter information and instructions into a
computer system. Data is transferred to the CPU for processing after inputting by an
input device.
2. Processing: It is the process of converting the raw data into useful information. This
process is performed by the CPU of the computer. It takes the raw data from storage,
processes it and then sends back the processed data to storage. The CPU performs
arithmetic computations, logical operations, and data transport processes.
3
3. Storing: The computer has primary memory and secondary storage to store data and
instructions. It stores the data before sending it to CPU for processing and also stores
the processed data before displaying it as output. The primary memory, sometimes
called RAM, is where the CPU processes the data and instructions. Hard disc drives
and solid-state drives, which serve as secondary memory, offer long-term storage for
data and programmes that are not currently used.
4. Outputting: It is the process of presenting the processed data through output devices
like monitor, printer and speakers. These devices display or produce the results of
the processing performed by the CPU. The results are sent to an output device for
display or printing after the CPU has finished processing the data and instructions.
5. Controlling: This operation is performed by the control unit that is part of CPU. The
control unit ensures that all basic operations are executed in a right manner and
sequence. The main circuit board connects all the parts of the computer. It also
regulates the data flow between them, ensuring they function properly and
connecting them all.
A decision problem is one where the answer is yes or no. For instance, "given a
number n, is n even?" is a decision problem. Some decision problems take more steps
to solve than others. For instance, "given a number n, is n prime?" takes more steps
than just checking the parity of a number.
A search problem is one where the solution consists of one or more values that
satisfies a given condition. For instance, we may want to compute a path from one
geographical location to another on a map.
A counting problem is one where the answer is the number of solutions to a search
problem.
An optimization problem is one where the solution is the "best" possible solution,
where the "best" can be defined in a different way. For instance, we may want to
compute the fastest route from one location to another.
3. 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
4
Correct program.
5
output data-processed result
2.2. State:
Transition from one process to another process under specified condition with in a
time is called state.
Sequence:
All the instructions are executed one after another is called sequence execution.
Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
Selection:
A selection statement causes the program control to be transferred to a specific
part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise
it will execute the other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
6
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
Iteration:
In some programs, certain set of statements are executed again and again based
upon conditional test. i.e. executed more than one time. This type of execution is called
looping or iteration.
Example
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
2.4. Functions:
Function is a sub program which consists of block of code(set of instructions)
that performs a particular task.
For complex problems, the problem is been divided into smaller and simpler
tasks during algorithm design.
Benefits of Using Functions
Reduction in line of code
code reuse
Better readability
Information hiding
Easy to debug and test
Improved maintainability
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
3. NOTATIONS
3.1.FLOW CHART
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.
8
4. Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.
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.
3.2.PSEUDO CODE:
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.
9
It is not a machine readable
Pseudo code can’t be compiled and executed.
There is no standard syntax for pseudo code.
10
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
statement GET n
... INITIALIZE i=1
ENDWHILE WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
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.
Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
Algorithm Flowchart Pseudo code
An algorithm is a sequence It is a graphical It is a language
of instructions used to representation of algorithm representation of
solve a problem algorithm.
User needs knowledge to not need knowledge of Not need knowledge of
write algorithm. program to draw or program language to
understand flowchart understand or write a
pseudo code.
3.3.PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer
to perform specific tasks. The programmers have to follow all the specified rules before
writing program using programming language. The user has to communicate with the
computer using language which it can understand.
Types of programming language
1. Machine language
11
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different
combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands. For
executing any program written in any programming language, the conversion to
machine language is necessary. The program written in machine language can be
executed directly on computer. In this case any conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time is
saved, the execution of machine language program is extremely fast.
Disadvantage:
It is hard to find errors in a program written in the machine language.
Writhing program in machine language is a time consuming process.
Machine dependent: According to architecture used, the computer differs from each
other. So machine language differs from computer to computer. So a program
developed for a particular type of computer may not run on other type of computer.
Assembly language:
To overcome the issues in programming language and make the programming
process easier, an assembly language is developed which is logically equivalent to
machine language but it is easier for people to read, write and understand.
Assembly language is symbolic representation of machine language. Assembly
languages are symbolic programming language that uses symbolic notation to
represent machine language instructions. They are called low level language
because they are so closely related to the machines.
Ex: ADD a, b
Assembler:
Assembler is the program which translates assembly language instruction in to a
machine language.
Advantage:
Easy to understand and use.
It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine depends
on the architecture of that computer.
Hard to learn
12
It is machine dependent, so the programmer should have the hardware
knowledge to create applications using assembly language.
Less efficient
Execution time of assembly language program is more than machine language
program.
Because assembler is needed to convert from assembly language to machine
language.
High level language
High level language contains English words and symbols. The specified rules are
to be followed while writing program in high level language. The interpreter or
compilers are used for converting these programs in to machine readable form.
Translating high level language to machine language
The programs that translate high level language in to machine language are called
interpreter or compiler.
Compiler:
A compiler is a program which translates the source code written in a high level
language in to object code which is in machine language program. Compiler reads the
whole program written in high level language and translates it to machine language. If
any error is found it display error message on the screen.
Interpreter
Interpreter translates the high level language program in line by line manner. The
interpreter translates a high level language statement in a source program to a machine
code and executes it immediately before translating the next statement. When an error
is found the execution of the program is halted and error message is displayed on the
screen.
Advantages
Readability
High level language is closer to natural language so they are easier to learn and
understand
Machine independent
High level language program have the advantage of being portable between
machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages
Less efficient
The translation process increases the execution time of the program. Programs in
high level language require more memory and take more execution time to execute.
Scripting language:
14
Scripting language are programming languages that control an application.
Scripts can execute independent of any other application. They are mostly embedded in
the application that they control and are used to automate frequently executed tasks
like communicating with external program.
Examples:
Apple script
VB script
Markup languages:
A markup language is an artificial language that uses annotations to text that
define hoe the text is to be displayed.
Examples:
HTML
XML
Concurrent programming language:
Concurrent programming is a computer programming technique that provides
for the execution of operation concurrently, either with in a single computer or across a
number of systems.
Examples:
Joule
Limbo
Object oriented programming language:
Object oriented programming is a programming paradigm based on the concept
of objects which may contain data in the form of procedures often known as methods.
Examples:
Lava
Moto
15
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.
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.
16
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.
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.
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.
18
5.2. 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.
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
19
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
More examples:
Write an algorithm to find area of a rectangle
20
Write an algorithm for Calculating simple interest
Step 1: Start
Step 2: get P, n, r value BEGIN
Step3:Calculate READ P, n, r
SI=(p*n*r)/100 CALCULATE S
Step 4: Display S SI=(p*n*r)/100
Step 5: Stop DISPLAY SI
END
21
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
22
To check positive or negative number
Step 1: Start
Step 2: get num
Step 3: check if(num>0) print a is positive
Step 4: else num is negative
Step 5: Stop
BEGIN
READ num
IF (num>0) THEN
DISPLAY num is positive
ELSE
DISPLAY num is negative
END IF
END
23
To check odd or even number
Step 1: Start
Step 2: get num
Step 3: check if(num%2==0) print num is even
Step 4: else num is odd
Step 5: Stop
BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END
24
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END
25
BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
END IF
END
26
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 8
Step 5: Print i value
step 6 : increment i value by 1
Step 7: go to step 4
Step 8: Stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
27
Write an algorithm to print n odd numbers
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check if(i<=n) goto step 5 else goto step 8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
28
Write an algorithm to print n even numbers
Step 1: start
step 2: get n value
step 3: set initial value i=2
step 4: check if(i<=n) goto step 5 else goto step8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
29
Write an algorithm to print squares of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
30
Write an algorithm to print to print cubes of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i *i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
31
Write an algorithm to find sum of a given number
Step 1: start
step 2: get n value
step 3: set initial value i=1, sum=0
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate sum=sum+i
step 6: increment i value by 1
step 7: goto step 4
step 8: print sum value
step 9: stop
BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
32
Write an algorithm to find factorial of a given number
Step 1: start
step 2: get n value
step 3: set initial value i=1, fact=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate fact=fact*i
step 6: increment i value by 1
step 7: goto step 4
step 8: print fact value
step 9: stop
BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
33
Basic python programs:
Addition of two numbers Output
a=eval(input(“enter first no”)) enter first no
b=eval(input(“enter second no”)) 5
c=a+b enter second no
print(“the sum is “,c) 6
the sum is 11
Area of rectangle Output
l=eval(input(“enter the length of rectangle”)) enter the length of rectangle 5
b=eval(input(“enter the breath of rectangle”)) enter the breath of rectangle 6
a=l*b 30
print(a)
Area & circumference of circle output
r=eval(input(“enter the radius of circle”)) enter the radius of circle4
a=3.14*r*r the area of circle 50.24
c=2*3.14*r the circumference of circle
print(“the area of circle”,a) 25.12
print(“the circumference of circle”,c)
Calculate simple interest Output
p=eval(input(“enter principle amount”)) enter principle amount 5000
n=eval(input(“enter no of years”)) enter no of years 4
r=eval(input(“enter rate of interest”)) enter rate of interest6
si=p*n*r/100 simple interest is 1200.0
print(“simple interest is”,si)
34
Find greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Programs on for loop
Print n natural numbers Output
print(i)
Print n odd numbers Output
for i in range(1,10,2):
13 5 79
print(i)
for i in range(1,5,1): 1 4 9 16
print(i*i)
for i in range(1,5,1): 1 8 27 64
print(i*i*i)
35
Print n natural numbers Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
5
Print n odd numbers Output
i=2 2
while(i<=10): 4
print(i) 6
i=i+2 8
10
Print n even numbers Output
i=1 1
while(i<=10): 3
print(i) 5
i=i+2 7
9
Print n squares of numbers Output
i=1 1
while(i<=5): 4
print(i*i) 9
i=i+1 16
25
36
factorial of n numbers/product of n numbers Output
i=1 3628800
product=1
while(i<=10):
product=product*i
i=i+1
print(product)
37
check the no divisible by 5 or not Output
def div(): enter n value10
n=eval(input("enter n value")) the number is divisible by
if(n%5==0): 5
print("the number is divisible by 5")
else:
print("the number not divisible by 5")
div()
38
program for basic calculator Output
def add(): enter a value 10
a=eval(input("enter a value")) enter b value 10
b=eval(input("enter b value")) the sum is 20
c=a+b enter a value 10
print("the sum is",c) enter b value 10
def sub(): the diff is 0
a=eval(input("enter a value")) enter a value 10
b=eval(input("enter b value")) enter b value 10
c=a-b the mul is 100
print("the diff is",c) enter a value 10
def mul(): enter b value 10
a=eval(input("enter a value")) the div is 1
b=eval(input("enter b value"))
c=a*b
print("the mul is",c)
def div():
a=eval(input("enter a value"))
b=eval(input("enter b value"))
c=a/b
print("the div is",c)
add()
sub()
mul()
div()
39