Вы находитесь на странице: 1из 20

How to write an algorithm

Write an algorithm to display the addition of two numbers :


STEP 1 – START;
STEP 2 – INPUT A,B;
STEP 3 – SET SUM = A+B;
STEP 4 – PRINT SUM;
STEP 5 – STOP;
Write an algorithm to calculate and print simple interest
:
STEP 1 – START;
STEP 2 – INPUT P,R,T;
STEP 3 – SET x=P*R*T;
STEP 4 – SET SI=x/100;
STEP 5 – PRINT SI;
STEP 6 – STOP;
Write an algorithm to calculate the area of sclane triangle :
STEP 1 – START;
STEP 2 – INPUT A,B,C;
STEP 3 – SET S=(A+B+C)/2;
STEP 4 – SET AREA={S(S-A)(S-B)(S-C)}1/2;
STEP 5 – PRINT AREA;
STEP 6 – STOP;
Flowchart
The flowchart shows the steps as boxes of various kinds, and
their order by connecting the boxes with arrows.
Comments
They are annotation made by the programmers. It helps to
debug the code and improve its understanding.
Any statement can be made into comments by adding ‘#’ at the
beginning of the statement.
It is not executable.
Identifiers
Its is a name given to a variable, class function, module or other
object.
Norms to write an identifier:
It can only begin with “A-Z” or “a-z” or ‘_’
It can include any number of letters digits or underscores.
Keywords
Python has some reserved words which are given some specific
meaning. Programmers are not allowed to change the meaning
of the keywords.
Variables
A variable holds a value that may change. In python, a variable
can be used with its corresponding identifiers to assign values
into it to print or to display the value.
Data types
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
Numeric
Divided into integers and real numbers i.e. fractional part and
non-fractional part
String
It allows to hold up a group of characters called string. String is
represented by a pair of single or double quotes.
List
A list can contain more than one item at once. These items can
be of same or different types. A list in python is an indexable
sequence. “[]” is used to declare a list and the items are
separated by “,”.
Type Conversion
Changing an object data type to another data type as per the
need.

Some functions are used in type conversion:


int() long() float() str() tuple() list()
dicr() unichr() chr() oct() set()
Typecasting
Changing the data type explicitly (by the user).
Coercion
Implicit conversion
Decision Making Statements
1. If statement
Syntax : if(condition):
Statements
2. If-else statement
Syntax : if (condition):
Statement
else:
statement
3. Nested if statement
Syntax : if(condition):
Statement
if(condition):
Statement
else:
Statement
4. If-elif statement
Syntax : if(condition):
Statement
elif(condition):
statement
Q.Write a programme to calculate the roots of a quadratic
equation, input coefficients of x2 ,x and constant and also print
the nature of the roots.

import math
a=input(“Enter the coefficient of x2”)
b=input(“Enter the coefficient of x”)
c=input(“Enter the constant term”)
root1=math.pow((-b+(math.pow(b,2))-4*a*c),0.5)/(2*a)
root2=math.pow((-b-(math.pow(b,2))-4*a*c),0.5)/(2*a)
x=math.pow(b,2)-4*a*c
if x==0:
print(“roots are positive and equal”)
elif x>0:
print(“roots are positive and distinct”)
elif c<0:
print(“no real rootsl”)
Iterated Statements
• While loop
• For loop
1. WHILE loop
It provides a mechanism to repeat one or more statements
while a particular statement is true.
Syntax : statement x #initialisation
while(condition):
statement
updation
statement
Write a programme to find the sum of first 15 natural number
a=0
x=1
while(x<=15)
print(x,’\t’)
x=x+1
2. FOR loop
It is used similar to while loop to iterate a task until a given
condition is true. For loop is best in case of knowing exactly the
no.of iterations that is a definite no.of steps.
Syntax : for <control variable> in sequence:
Statement
Statements
range()
Built-in function that is used to iterate over a sequence of a
number.
Syntax : range(beginning, end,[step])
Break Statement
Keyword used to terminate the loop execution of the current
loop.
Continue Statement
Keyword used to skip an iteration of the current loop.
Pass Statement
Used when a statement is required syntactically not logically. It
specifies a null operation.

Special Properties of Strings


1. indexing()
Each character can be accessed using a specific index value.
2. Strings are Immutable
It means that a string’s character cannot be assigned a value
separately.
3. Concatenation
Strings are very useful due to the concat feature as we can add
required characters in the end of a string.
4. Appending
The appending operations used to add characters on another
string at the end of the string.
5. Multiplying
A string can be repeated any no.of times using the
multiplication operator
6. str()
It is used t convert a sequence of characters into a string.
7. input()
Used to accept user input in form of string.
8. raw_output
To print a string as it is with all the characters as it is.
9. len()
this function finds out the length of the string.
10. Doc String
This is used for a documentation purpose and hence can spam
up to several lines. Unlike the single line comment character it
is implanted with triple quotes.
11. String Traversal
A string being a sequence can be traversed character by
character.
More Python data types
List

In Python programming, a list is created by placing all the items


(elements) inside a square bracket [ ], separated by commas.

It can have any number of items and they may be of different


types (integer, float, string etc.).

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called
nested list.

# nested list

my_list = ["mouse", [8, 4, 6], ['a']]

tuple

In Python programming, a tuple is similar to a list. The


difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas in a list,
elements can be changed.

A tuple is created by placing all the items (elements) inside a


parentheses (), separated by comma. The parentheses are
optional but is a good practice to write it.

A tuple can have any number of items and they may be of


different types (integer, float, list, string etc.).

Example
my_tuple = (1, 2, 3)
print(my_tuple)
(1,2,3)
String
A string is a sequence of characters.

Strings can be created by enclosing characters inside a single


quote or double quotes. Even triple quotes can be used in
Python but generally used to represent multiline strings and
docstrings.

Example
my_string = 'Hello'
print(my_string)
output
‘Hello’
Sets

A set is an unordered collection of items. Every element is


unique (no duplicates) and must be immutable (which cannot
be changed).

However, the set itself is mutable. We can add or remove items


from it.

Sets can be used to perform mathematical set operations like


union, intersection, symmetric difference etc.

A set is created by placing all the items (elements) inside curly


braces {}, separated by comma or by using the built-in
function set().

It can have any number of items and they may be of different


types (integer, float, tuple, string etc.). But a set cannot have a
mutable element, like list, set or dictionary, as its element.
Example

my_set = {1, 2, 3}

print(my_set)

output

{1,2,3}

Dictionary

Python dictionary is an unordered collection of items. While


other compound data types have only value as an element, a
dictionary has a key: value pair.

Dictionaries are optimized to retrieve values when the key is


known.

Creating a dictionary is as simple as placing items inside curly


braces {} separated by comma.

An item has a key and the corresponding value expressed as a


pair, key: value.

Example

my_dict = {1: 'apple', 2: 'ball'}

What is a function in Python?

In Python, function is a group of related statements that


perform a specific task.

Functions help break our program into smaller and modular


chunks. As our program grows larger and larger, functions
make it more organized and manageable.
Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

example

def greet(name):

"""This function greets to

the person passed in as

parameter"""

print("Hello, " + name + ". Good morning!")

greet('Paul')

Hello, Paul. Good morning!

What is recursion in Python?

Recursion is the process of defining something in terms of


itself.

A physical world example would be to place two parallel


mirrors facing each other. Any object in between them would be
reflected recursively.
# An example of a recursive function to

# find the factorial of a number

def calc_factorial(x):

"""This is a recursive function

to find the factorial of an integer"""

if x == 1:

return 1

else:

return (x * calc_factorial(x-1))

num = 4

print("The factorial of", num, "is", calc_factorial(num))

output

The factorial of 4 is 24

object-oriented programming
Python is an object-oriented programming language.
What this means is we can solve a problem in Python by
creating objects in our programs.
Object
An object is an entity that has attributes and behaviour. For
example, Ram is an object who has attributes such as height,
weight, color etc. and has certain behaviours such as walking,
talking, eating etc.

Class
A class is a blueprint for the objects. For example, Ram, Shyam,
Steve, Rick are all objects so we can define a template
(blueprint) class Human for these objects. The class can define
the common attributes and behaviours of all the objects.

Methods
As we discussed above, an object has attributes and behaviours.
These behaviours are called methods in programming.

Example of Class and Objects


In this example, we have two objects Ram and Steve that belong
to the class Human
Object attributes: name, height, weight
Object behaviour: eating()

class Human:
# instance attributes
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight

# instance methods (behaviours)


def eating(self, food):
return "{} is eating {}".format(self.name, food)

# creating objects of class Human


ram = Human("Ram", 6, 60)
steve = Human("Steve", 5.9, 56)
# accessing object information
print("Height of {} is {}".format(ram.name, ram.height))
print("Weight of {} is {}".format(ram.name, ram.weight))
print(ram.eating("Pizza"))
print("Weight of {} is {}".format(steve.name, steve.height))
print("Weight of {} is {}".format(steve.name, steve.weight))
print(steve.eating("Big Kahuna Burger"))
Output:

Height of Ram is 6
Weight of Ram is 60
Ram is eating Pizza
Weight of Steve is 5.9
Weight of Steve is 56
Steve is eating Big Kahuna Burger

Inheritance

Inheritance is the most important aspect of object-oriented


programming which simulates the real world concept of
inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.

By using inheritance, we can create a class which uses all the


properties and behavior of another class. The new class is
known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.

It provides re-usability of the code.

Polymorphism

Polymorphism contains two words "poly" and "morphs". Poly


means many and Morphs means form, shape. By
polymorphism, we understand that one task can be performed
in different ways. For example You have a class animal, and all
animals speak. But they speak differently. Here, the "speak"
behavior is polymorphic in the sense and depends on the
animal. So, the abstract "animal" concept does not actually
"speak", but specific animals (like dogs and cats) have a
concrete implementation of the action "speak".

Encapsulation

Encapsulation is also an important aspect of object-oriented


programming. It is used to restrict access to methods and
variables. In encapsulation, code and data are wrapped together
within a single unit from being modified by accident.

Data Abstraction

Data abstraction and encapsulation both are often used as


synonyms. Both are nearly synonym because data abstraction is
achieved through encapsulation.

Data Structure

a data structure is a data organization, management and


storage format that enables efficient access and
modification.More precisely, a data structure is a collection
of data values, the relationships among them, and the functions
or operations that can be applied to the data.
here are numerous types of data structures,

 An array is a number of elements in a specific order,


typically all of the same type (depending on the language,
individual elements may either all be forced to be the same
type, or may be of almost any type). Elements are accessed
using an integer index to specify which element is
required. Typical implementations allocate contiguous
memory words for the elements of arrays (but this is not
always a necessity). Arrays may be fixed-length or
resizable.
 A linked list (also just called list) is a linear collection of
data elements of any type, called nodes, where each node
has itself a value, and points to the next node in the linked
list. The principal advantage of a linked list over an array,
is that values can always be efficiently inserted and
removed without relocating the rest of the list.
 Stack is a linear data structure which follows a particular
order in which the operations are performed. The order
may be LIFO(Last In First Out) or FILO(First In Last Out).
 A Queue is a linear structure which follows a particular
order in which the operations are performed. The order is
First In First Out (FIFO). The difference
between stacks and queues is in removing. In a stack we
remove the item the most recently added; in a queue, we
remove the item the least recently added.

 A binary tree data structure is tree whose elements have at


most 2 children is called a binary tree. Since each element
in a binary tree can have only 2 children, we typically
name them the left and right child.

Searching and sorting

Selection Sort Algorithm

The Selection Sort algorithm is based on successive selection of


minima or maxima values. Assume that we have a list which we
want to sort in ascending order (from smaller to larger values).
The smallest element will be at the beginning of the list, and the
largest element will be at the end of the list.

Bubble Sort
This simple sorting algorithm iterates over a list, comparing
elements in pairs and swapping them until the larger elements
"bubble up" to the end of the list, and the smaller elements stay
at the "bottom".
Insertion Sort
Like Selection Sort, this algorithm segments the list into sorted
and unsorted parts. It iterates over the unsorted segment, and
inserts the element being viewed into the correct position of the
sorted list.

Heap Sort
This popular sorting algorithm, like the Insertion and Selection
sorts, segments the list into sorted and unsorted parts. It
converts the unsorted segment of the list to a Heap data
structure, so that we can efficiently determine the largest
element.

Merge Sort
This divide and conquer algorithm splits a list in half, and keeps
splitting the list by 2 until it only has singular elements.

Adjacent elements become sorted pairs, then sorted


pairs are merged and sorted with other pairs as well.
This process continues until we get a sorted list with
all the elements of the unsorted input list. Merge Sort
This divide and conquer algorithm splits a list in half, and keeps
splitting the list by 2 until it only has singular elements.

Adjacent elements become sorted pairs, then sorted pairs are


merged and sorted with other pairs as well. This process
continues until we get a sorted list with all the elements of the
unsorted input list.
Linear Search Algorithm

The Linear Search algorithm is a simple algorithm, where each


item in the list (starting from the first item) is investigated until
the required item is found, or the end of the list is reached.

Binary Search

We basically ignore half of the elements just after one


comparison.
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie
in right half subarray after the mid element. So we recur for
right half.
4. Else (x is smaller) recur for the left half.

Algorithm Design Techniques

Greedy is an algorithmic paradigm that builds up a solution


piece by piece, always choosing the next piece that offers the
most obvious and immediate benefit. Greedy algorithms are
used for optimization problems. An optimization problem can
be solved using Greedy if the problem has the following
property: At every step, we can make a choice that looks best
at the moment, and we get the optimal solution of the complete
problem.

Dynamic Programming is an algorithmic paradigm that


solves a given complex problem by breaking it into
subproblems and stores the results of subproblems to avoid
computing the same results again
like Greedy and Dynamic Programming, Divide and
Conquer is an algorithmic paradigm. A typical Divide and
Conquer algorithm solves a problem using following three
steps.
1. Divide: Break the given problem into subproblems of same
type.
2. Conquer: Recursively solve these subproblems
3. Combine: Appropriately combine the answers

Backtracking Algorithm: Backtracking Algorithm tries each


possibility until they find the right one. It is a depth-first search
of the set of possible solution. During the search, if an
alternative doesn't work, then backtrack to the choice point, the
place which presented different alternatives, and tries the next
alternative.

Branch and Bound: In Branch & Bound algorithm a given


subproblem, which cannot be bounded, has to be divided into
at least two new restricted subproblems. Branch and Bound
algorithm are methods for global optimization in non-convex
problems. Branch and Bound algorithms can be slow, however
in the worst case they require effort that grows exponentially
with problem size, but in some cases we are lucky, and the
method coverage with much less effort.

Вам также может понравиться