0% found this document useful (0 votes)
9 views

UNIT 1 python

Uploaded by

keerthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

UNIT 1 python

Uploaded by

keerthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

24ECS102 PYTHON PROGRAMMING

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING

Fundamentals of computing –Identification of Computational Problem-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).

1. Fundamentals of computing

 A computer is an electronic device that accepts data/inputs from its user and processes
it into useful information as per the processing instructions to generate the output.

 Functionalities of Computer

 If we consider it in a very broad sense, any digital computer performs the following
five operations:

Step 1 − Accepts data as input.

Step 2 − Saves the data/instructions in its memory and utilizes them as and when required.

Step 3 − Execute the data and convert it into useful information.

Step 4 − Provides the output.

Step 5 − Have control over all the above four steps

1
1.1 Generation of Computers

1. Input / Output Unit:

Input Unit:
 It accepts the data from the user

 It converts the data into a form that is understandable by the computer

 The input is given to the computer through the devices like keyboard, mouse, touch screen
etc..
Output Unit:
- It provides the processed data (information) to the user,

- It is understandable by the user

- Some output devices are monitor, printer and speaker.

2. Central Processing Unit : (CPU)

- CPU or the processor is often called as the brain of the computer

- It controls, coordinates and supervises the operations of the computer

- It consists of

(i). Arithmetic and Logic Unit (ALU)

(ii). Control Unit (CU)

(iii). Set of registers

2
(i). Arithmetic and Logic Unit:

• ALU consists of 2 units. They are arithmetic unit and logic unit.

• The Arithmetic unit performs arithmetic operations on the data like addition,

subtraction, multiplication and division.


• The logic unit performs logic operations like comparing and testing.

(ii). Control Unit(CU)

• The control unit organizes the processing of data and instructions.

• It acts as a supervisor, controls and coordinates the activity of the other units of computer

(iii). Registers

• Registers are high speed storage area within CPU

• Registers store data, instructions, addresses and intermediate results of processing.

So, registers are often called as CPU’s working memory.


• The data and instructions that require processing must be brought in the registers of

CPU before they can be processed.


• Some of the important registers are

ACC : Accumulator stores the result of arithmetic and logical operations


IR : Instruction register contains the current instruction most recently
fetched PC : Program counter contains the address of next instruction
to be executed MAR : Memory Address register
MBR : Memory Buffer register
DR : Data Register
3. Memory Unit:
Cache Memory:
• Cache memory is placed between RAM and CPU.

• Frequently used instructions are stored in it.

• It is very fast , expensive and smaller.

3
Primary Memory:
Primary memory is the main memory of computer. It is used to store data and instructions during
the processing.
It is of 2 kinds: RAM and ROM
RAM:
• RAM is volatile

• It stores data when computer is on, so it is a temporary storage

• It provides limited storage capacity due to its high cost

ROM:
• ROM is non-volatile and read only memory.

• It is a permanent storage

• It comes programmed by the manufacturer.

Secondary Memory:
• The secondary memory stores data and instructions permanently.

• It is non-volatile memory

• Examples: Hard disk drive, floppy drive and optical disk drive

• It takes longer time to access data. It has high storage capacity

• It is cheaper than RAM

Applications:
• Science

• Education

• Medical and Health Care

• Engineering/Architecture/Manufacturing

• Entertainment

• Communication

• Business Application

• Publishing

• Banking

4
1.2 TYPES OF COMPUTERS

PC/Personal Computer

These are single-user computer systems having small, relatively reasonable computers
designed for an individual user. This type of computer can easily be moved from one place
to the other comprising a personal storage unit, input & output unit, and a Central
Processing Unit.

Workstation

Regularly a single user system is named a workstation. Workstations usually come with a
high-resolution graphics screen, inbuilt network support, a large amount of RAM, and a
graphical user interface. They are often designed for self-use by an individual and can be
used for multiple purposes. This type of system is not convenient for carrying from one
place to another.

Mini Computer

These come under multiple user computer systems that are capable of holding hundreds of
users simultaneously.

Main Frame

Mainframe computers are also multi-user computer systems, capable of supporting


hundreds of users simultaneously; designed to be used in large firms and organizations
where a lot of people have to work on the same database. Software technology is different
from minicomputers.

Supercomputer

These are extremely fast computers, which can execute hundreds of millions of
instructions per second. Supercomputers are mostly used in scientific and engineering
operations where processing is difficult. They are costly and complex to work on.

1.3 INTRODUCTION TO COMPUTATIONAL PROBLEMS

Computational problem identification consists of 2 steps

Identifying and acknowledging that there is a problem

Developing a problem identification statement

5
We need to four steps related to the identification of problem and its solutions. They are
decomposition, pattern recognition, abstraction, and algorithm design.

Decomposition:

The first step of computational thinking is decomposition. This stage stars by analyzing the
problem, stating it precisely, and establishing the criteria for the solution.

A computational thinking approach to a solution often starts by breaking the problem down
into smaller more familiar components so they can managed easier. The more you can
break a problem down, the easier it to be solve.

Pattern recognition:

Similarities and trends are identified within the problem.

If some problems are similar in nature, there is a good chance that they can be solved using
similar or repeated techniques.

This is a key component for making efficient solutions, and saving time in effective
solutions to given problems.

Abstraction:

The abstraction stage involves the identification of key components of the solution

It requires the ability to filter out unnecessary elements of a problem so that only focus on
the important elements.

Algorithm Design:

The final stage within the computational thinking process is algorithm design whereby a
detailed step by step set of instructions are created which explain how to solve the problems

Problem
2.ALGORITHM BUILDING BLOCKS OF ALGORITHMS (statements, state, control
flow, functions)
Algorithms can be constructed from basic building blocks namely, sequence,selection
and iteration.

6
2.1. Statements:
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

2.2. State:
Transition from one process to another process under specified condition with in atime is
called state.

2.3. Control flow:


The process of executing the individual statements in a given order is called controlflow.
The control can be executed in three ways
1. sequence
2. selection
3. iteration

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:

7
A selection statement causes the program control to be transferred to a specificpart of

8
the program based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwiseit 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
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
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 7 Step
5: Print i value and increment i value by 1Step 6:
9
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 simplertasks
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

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return

10
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 visualrepresentation.

11
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
flowlines may leave the decision symbol.

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.

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
12
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 mayrequire
re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction offlowchart
becomes a problem.
4. Cost: For large application the time and cost of flowchart drawing becomescostly.
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.
It is not a machine readable
Pseudo code can’t be compiled and
executed. There is no standard syntax for
pseudo code.
Guidelines for writing pseudo code:
Write one statement per line
Capitalize initial keyword
Indent to hierarchy
End multiline structure
Keep statements language independent
Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
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.

13
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.

14
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.
FOR, ENDFOR: Another iterative Example: Greates of two numbers
incremented/decremented tested
automatically.Syntax for if else:
IF (condition)THEN BEGIN
statement READ
... a,b
ELS IF (a>b) THEN
E DISPLAY a is greater
statement ELSE
... DISPLAY b is greater
ENDIF END IF
END
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGI
statement N GET
... n
ENDFO INITIALIZE
R i=1 FOR (i<=n)
DOPRINT i
i=i+1
ENDFO
REND
Syntax for While: Example: Print n natural numbers

15
WHILE (condition) DO BEGI
statement N GET
... n
ENDWHILE INITIALIZE i=1
WHILE(i<=n)
DO
PRINT i
i=i+1
ENDWHIL
E
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 comparedwith
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

16
PRINT

17
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
beforewriting 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
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

18
speed

19
The machine language program is translation free. Since the conversion time issaved,
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 eachother. 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 tomachine
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 dependson the
architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the hardware
knowledge to create applications using assembly language.
Less efficient

20
 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 areto
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. Ifany
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 erroris 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
21
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.

They are divided into following categories:


1. Interpreted programming languages
2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Scripting programming language
6. Markup programming language
7. Concurrent programming language
8. Object oriented programming language

Interpreted programming languages:


An interpreted language is a programming language for which most of its
implementation executes instructions directly, without previously compiling a programinto
machine language instructions. The interpreter executes the program directly translating each
statement into a sequence of one or more subroutines already compiled into machine code.
Examples:
Pascal
Python

Functional programming language:


Functional programming language defines every computation as a mathematical
evaluation. They focus on the programming languages are bound to mathematical
calculations Examples:
Clean
Haskell

Compiled Programming language:


22
A compiled programming is a programming language whose implementation are
typically compilers and not interpreters.
It will produce a machine code from source code.
Examples:
C
C++
C#
JAV
A

Procedural programming language:


Procedural (imperative) programming implies specifying the steps that the programs
should take to reach to an intended state.
A procedure is a group of statements that can be referred through a procedure call.
Procedures help in the reuse of code. Procedural programming makes the programs
structured and easily traceable for program flow.
Examples:
Hyper talk
MATLAB

Scripting language:
Scripting language are programming languages that control an application. Scripts can
execute independent of any other application. They are mostly embedded inthe application
that they control and are used to automate frequently executed tasks like communicating with
external program.

Examples:
Apple script
VB script

Markup languages:

23
A markup language is an artificial language that uses annotations to text thatdefine
hoe the text is to be displayed.
Examples:
HTM
L
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 anumber of
systems.
Examples:
Joule
Limbo
Object oriented programming language:
Object oriented programming is a programming paradigm based on the conceptof
objects which may contain data in the form of procedures often known as methods.

Examples:
Lava
Moto

24
4. ALGORITHMIC PROBLEM SOLVING:
Algorithmic Problem solving is solving problem that require the formulation of analgorithm

for the solution.


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 tohandle.
 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

 If the instructions are executed one after another, it is called sequentialalgorithm.

25
 If the instructions are executed concurrently, it is called parallel algorithm.
Choosing between Exact and Approximate Problem Solving
 The next principal decision is to choose between solving the problem exactly
orsolving 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 dataspecifying
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 problems 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

26
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’simplementation.
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.
 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.

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 analyzing the results obtained.

27
5. SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:
1. iterations
2. Recursions
5.1. Iterations:
A sequence of statements is executed until a specified condition is true is callediterations.
1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
BEGI
FOR( start-value to end-value) DO N GET
statement n
... INITIALIZE
ENDFO i=1 FOR (i<=n)
R DOPRINT i
i=i+1
ENDFO
REND
Syntax for While: Example: Print n natural numbers
BEGI
WHILE (condition) DO N GET
statement n
... INITIALIZE i=1
ENDWHILE WHILE(i<=n)
DO
PRINT i
i=i+1
ENDWHIL
EEND

28
5.2. Recursions:
 A function that calls itself is known as recursion.
 Recursion is a process by which a function calls itself repeatedly until
somespecified condition has been satisfied.
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

29
Step2: else fact=n*factorial(n-1) and return fact

30
Pseudo code for factorial using recursion:
Main function:
BEGI
N
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)

31

You might also like