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

python unit one notes.docx

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

python unit one notes.docx

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

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.
PROBLEM SOLVING TECHNIQUES
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
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
1. 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.

Qualities of a good algorithm

The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is
the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem,
some of these may provide more accurate results than others, and such algorithms may be suitable

Building Blocks of Algorithm


As algorithm is a part of the blue-print or plan for the computer program. An algorithm is constructed
using following blocks.
● Statements
● States
● Control flow
● Function
Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may
consists of assignment statements, input/output statements, comment statements
Example:
● Read the value of ‘a’ //This is input statement
● Calculate c=a+b //This is assignment statement
● Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.

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
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow

Sequential control flow:


The name suggests the sequential control structure is used to perform the action one after
another. Only one step is executed once. The logic is top to bottom approach.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop
Selection or Conditional control flow
Selection flow allows the program to make choice between two alternate paths based on
condition. It is also called as decision structure
Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of two
numbers.
Example
Description: finding the greater number
1. Start
2. Read a
3. Read b
4. If a>b then
4.1. Print a is
greater else
4.2. Print b is greater
5. Stop

Repetition control flow


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 one more
instructions may need to be executed several times or depending on condition.
Basic Structure:
Repeat untilCONDITIONis true
Statements
Example
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n

4.1. Print i
5. 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:
1. Name for declaration of function
2. Body consisting local declaration and statements
3. Formal parameter
4. Optional result type.
Basic Syntax
function_name(parameters)
function statements
end function

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()
Step1:Functionstart
Step2:Geta,bValues
Step 3: add c=a+b
Step 4: Printc
Step 5: Return

2. NOTATIONS OF AN ALGORITHM
Algorithm can be expressed in many different notations, including Natural Language, Pseudo
code, flowcharts and programming languages. Natural language tends to be verbose and
ambiguous. Pseudocode and flowcharts are represented through structured human language.
A notation is a system of characters, expressions, graphics or symbols designs used among
each others in problem solving to represent technical facts, created to facilitate the best result for a
program
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
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to read the
input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE,
ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects RAED
name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
ELSE ENDIF PRI

NT a

is

great

er

PRI

NT b

is

great

er

5. Keep statements language independent.


Pesudocode must never written or use any syntax of any programming language.

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
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.
Table 1: Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.
2. Input/ Output Parallelogram Denotes either input or
symbol output operation.

3. Process symbol Rectangle Denotes the process to be


carried

4. Decision symbol Diamond Represents decision


making and branching

5. Flow lines Arrow lines Represents the sequence


of steps and direction of
flow. Used to connect
symbols.
6. Connector Circle A connector symbol is
represented by a circle
and a letter or digit is
placed in the circle to
specify the link. This
symbol is used to
connect flowcharts.

Rules for drawing flowchart


1. In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
2. The flow chart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or top to
bottom.
Only one flow line should come out from a process symbol.

4. 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.

5. Only one flow line is used in conjunction with terminal symbol.

6. If flowchart becomes complex, it is better to use connector symbols to reduce the number
of flow lines.
7. 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 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.
Control Structures using flowcharts and Pseudocode
Sequence Structure
Pseudocode Flow Chart
General Structure
Process 1
…. Process 1
Process 2

Process 2
Process 3

Process 3

Example
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… 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
Iteration or Looping Structure
● Looping is generally used with WHILE or DO...WHILE or FOR loop.
● WHILE and FOR is entry checked loop

Pseudocode Flow Chart


General Structure
WHILE condition
Body of the loop No
ENDWHILE if(condition)

Yes
Body of the loop

Example

● DO…WHILE is exit checked loop, so the loop will be executed at least once.
INITIALIZE a=1 Start

WHILE a<10 THEN


PRINT a
a=1
a=a+1
ENDWHILE
No
if (a<10)

Yes
Stop

Print a

a=a+1

o In python DO…WHILE is not supported.


o If the loop condition is true then the loop gets into infinite loop, which may lead to system crash

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.
Types of Programming Language
In general Programming languages are classified into three types. They are
● Low – level or Machine Language
● Intermediate or Assembly Language
● High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers. It is also
called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions and
variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y
High – level Language:
A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that
enables a programmer to write programs that are more or less independent of a particular type of
computer. Such languages are considered high-level because they are closer to human languages and further
from machine languages. Ultimately, programs written in a high-level language must be translated into
machine language by a compiler or interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below.

Language Type Example


Interpreted Programming Language Python, BASIC, Lisp
Functional Programming Language Clean, Curry, F#
Compiled Programming Language C++,Java, Ada, ALGOL
Procedural Programming Language C,Matlab, CList
Scripting Programming Language PHP,Apple Script, Javascript
Markup Programming Language HTML,SGML,XML
Logical Programming Language Prolog, Fril
Concurrent Programming Language ABCL, Concurrent PASCAL
Object Oriented Programming Language C++,Ada, Java, Python
Interpreted Programming Language:
Interpreter is a program that executes instructions written in a high-level language.
An interpreter reads the source code one instruction or one line at a time, converts this line into machine
code and executes it.

Compiled Programming Languages


Compile is to transform a program written in a high-level programming language from source code into
object code. This can be done by using a tool called compiler.
A compiler reads the whole source code and translates it into a complete machine code program to
perform the required tasks which is output as a new file.

Figure: Compiler
Interpreted vs. Compiled Programming Language
Interpreted Programming Language Compile Programming Language
Translates one statement at a time Scans entire program and translates it as whole
into machine code
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower comparatively faster
No intermediate object code is generated, hence Generates intermediate object code which
are memory efficient further requires linking, hence requires more
memory
Continues translating the program until first error It generates the error message only after
is met, in which case it stops. Hence scanning the whole program. Hence debugging
debugging is easy. is comparatively hard.
Eg: Python, Ruby Eg: C,C++,Java

ALGORITHMIC PROBLEM-SOLVING

The algorithmic problem-solving approach is the process of taking a problem and


developing a step by step procedure to solve it.
The main goal is to create an efficient solution that works within given constraints.
1. Understand the Problem
● Read and Analyze: Carefully read the problem statement and identify what is being asked.
● Define Inputs and Outputs: Clarify the format of the input data and the required output.
● Identify Constraints: Determine any limitations or constraints on the problem (e.g., time
limits, space limits).
● Example: To find the largest element in a list
2. Formulate the plan
● Break the problem down into smaller, well-defined tasks or steps.
● Identify the sub-problems or specific actions that need to be performed to solve the overall
problem.
● Example: For finding the largest number in a list:
● Start by assuming the first number is the largest.
● Compare each subsequent number with the current largest, updating the largest when
necessary
3. Designing an Algorithm
● Create a clear and efficient algorithm (step-by-step process) to solve the problem.
● Focus on writing down the steps in a clear, logical order.
● Example: To find the maximum number in a list, the algorithm could be:
● Set the first element as the maximum.
● Loop through each number in the list.
● If any number is greater than the current maximum, update the maximum.
4. Choosing the Right Strategy
● Decide which algorithmic approach (strategy) is best suited for the problem.
● There are multiple strategies available depending on the problem type.
● Common strategies include brute force, greedy algorithms, dynamic programming, divide
and conquer, recursion, and backtracking.
● Example: To sort a list, you might choose a divide-and-conquer strategy like Merge Sort if
efficiency is important, or a simpler algorithm like Bubble Sort for small datasets.
5. Implementing the Algorithm
● Convert your algorithm into code using a programming language.
● Ensure that the algorithm handles all cases, including edge cases (e.g., an empty list, very
large numbers, or specific constraints).
● Example: Once the algorithm to find the maximum number is designed, you implement it
in Python, C++, or any programming language
6. Testing and Debugging
● Test your algorithm with a variety of input cases to ensure it works as expected.
● Identify and fix any bugs or issues.
● Example: Test the maximum-finding algorithm with lists that have negative numbers, all
equal numbers, or an empty list to see how the algorithm handles edge cases.
7. Optimizing the Algorithm
● Analyze the algorithm’s time and space complexity (using
Big-O notation) and see if it can be optimized.
● Try to make the algorithm more efficient by reducing the number of steps or memory
usage.

You might also like