0% found this document useful (0 votes)
31 views35 pages

Computer

Uploaded by

Stove Archon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views35 pages

Computer

Uploaded by

Stove Archon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

CHAPTER-1

FUNCTIONS IN PYTHON
1.1 Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.

1.2 Types of Functions:


There are two types of functions in python:
1. Library Functions (Built in functions)
2. Functions defined in modules
3. User Defined Functions

Built in functions

Functions defined in
Types of functions modules

User defined functions

1. Library Functions: These functions are already built in the python library.

2. Functions defined in modules: These functions defined in particular modules. When


you want to use these functions in program, you have to import the corresponding module
of that function.

3. User Defined Functions: The functions those are defined by the user are called user
defined functions.

1. Library Functions in Python:


These functions are already built in the library of python.
For example: type( ), len( ), input( ) etc.
Page 2
2. Functions defined in modules:
a. Functions of math module:
To work with the functions of math module, we must import math module in
program. import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668

b. Function in random module:


random module has a function randint( ).
  randint( ) function generates the random integer values including start and end values. 
  Syntax: randint(start, end) 
 
It has two parameters. Both parameters must have integer values.

Example:
import random
n=random.randint(3,7)

*The value of n will be 3 to 7.

3. USER DEFINED FUNCTIONS:


The syntax to define a function is:
def function-name ( parameters) :
#statement(s)

Page 3
Where:
 
 Keyword def marks the start of function header.

 A function name to uniquely  identify it. Function naming follows the same rules of
writing identifiers in Python.
 
 Parameters (arguments) through which we pass values to a function. They are optional.
 
 A colon (:) to mark the end of function header.


 
One or more valid python statements that make up the function body. Statements must
have same indentation level.
 
An optional return statement to return a value from the function.

Example:

def display(name):

print("Hello " + name + " How are you?")

1.3 Function Parameters:


A functions has two types of parameters:
1. Formal Parameter: Formal parameters are written in the function prototype and function
header of the definition. Formal parameters are local variables which are assigned values from
the arguments when the function is called.
2. Actual Parameter: When a function is called, the values that are passed in the call are
called actual parameters. At the time of the call each actual parameter is assigned to the
corresponding formal parameter in the function definition.
Example :
def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.

Page 4
1.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.

Syntax:
function-name(parameter)
Example:
ADD(10,20)

OUTPUT:
Sum = 30.0

How function works?

def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)

… .. …
… .. …

The return statement:


The return statement is used to exit a function and go back to the place from where it was
called.
There are two types of functions according to return statement:
a. Function returning some value (non-void function) b.
Function not returning any value (void function)
Page 5
a. Function returning some value (non-void function) :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x

Example-2 Function returning multiple values:


def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple
print(S)

OUTPUT:
(7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)

Page 6
OUTPUT:
Hello
None

1.5 Scope and Lifetime of variables:

Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.

There are two types of scope for variables:

1. Local Scope

2. Global Scope

1. Local Scope: Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.

2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.

Example:

def my_func():
x = 10
print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)

OUTPUT:

Value inside function: 10

Value outside function: 20

Page 7
Here, we can see that the value of x is 20 initially. Even though the function my_func()changed
the value of x to 10, it did not affect the value outside the function.

This is because the variable x inside the function is different (local to the function) from the one
outside. Although they have same names, they are two different variables with different scope.

On the other hand, variables outside of the function are visible from inside. They have a global
scope.

We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
using the keyword global.

Programs related to Functions in Python topic:


1. Write a python program to sum the sequence given below. Take the input n from the user.
1 1 1 1

1+ 1!
+ 2!
+ 3!
+⋯+ !

Solution:
def fact(x):
j=1
res=1
while j<=x:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
2. Write a program to compute GCD and LCM of two numbers
def gcd(x,y):
while(y):
x, y = y, x % y
return x

def lcm(x, y):


lcm = (x*y)//gcd(x,y)
return lcm

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))

print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))


print("The G.C.D. of", num1,"and", num2,"is", gcd(num1, num2))
CHAPTER-2

FILE HANDLING

3.1 INTRODUCTION:

File:- A file is a collection of related data stored in a particular area on the disk.
Stream: - It refers to a sequence of bytes.
File handling is an important part of any web application.
3.2 Data Files:
Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line includes a
sequence of characters.
2. Binary Files : A binary file is any type of file that is not a text file.

S.
No. Text Files Binary Files

Stores information in the same format


1. Stores information in ASCII characters. which the information is held in
memory.

Each line of text is terminated with a


2. special character known as EOL (End of No delimiters are used for a line.
Line)

Some internal translations take place


3. when this EOL character is read or No translation occurs in binary files.
written.

Binary files are faster and easier for a


4. Slower than binary files. program to read and write the text
files.

3.3 Opening and closing a file:


3.3.1 Opening a file:
To work with a file, first of all you have to open the file. To open a file in
python, we use open( ) function.
Page 13
The open( ) function takes two parameters; filename, and mode. open( ) function returns a file
object.
Syntax:
file_objectname= open(filename, mode)

Example:
To open a file for reading it is enough to specify the name of the file:
f = open("book.txt")
The code above is the same as:
f = open("book.txt", "rt")
Where "r" for read mode, and "t" for text are the default values, you do not need to specify
them.

3.3.2 Closing a file:


After performing the operations, the file has to be closed. For this, a close( ) function is used to
close a file.
Syntax:
file-objectname.close( )

3.4 File Modes:

Text Binary
file File Description
mode Mode

‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file does not
exist.

‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not exist

‘a’ ‘ab’ Append - Opens a file for appending, creates the file if it does not exist

‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.

‘w+’ ‘wb+’ Read and Write-File is created if does not exist.

‘a+’ ‘ab+’ Read and write-Append new data

‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file exists

Page 14
In addition you can specify if the file should be handled as binary or text mode
“t” – Text-Default value. Text mode
“b” – Binary- Binary Mode (e.g. images)

3.5 WORKING WITH TEXT FILES:

3.5.1 Basic operations with files:


a. Read the data from a file
b. Write the data to a file
c. Append the data to a file
d. Delete a file

a. Read the data from a file:


There are 3 types of functions to read data from a file.
 
 read( ) : reads n bytes. if no n is specified, reads the entire file.
 
 readline( ) : Reads a line. if n is specified, reads n bytes.
 
readlines( ): Reads all lines and returns a list.

Steps to read data from a file:


 Create and Open a file using open( ) function

 use the read( ), readline( ) or readlines( ) function

 print/access the data

 Close the file. Create and Open a file

Read or Write data

Print/Access data

Close the file

Page 15
Let a text file “Book.txt” has the following text:
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”

Example-1: Program using read( ) function:

fin=open("D:\\python programs\\Book.txt",'r') fin=open("D:\\python programs\\Book.txt",'r')


str=fin.read( ) str=fin.read(10)
print(str) print(str)
fin.close( ) fin.close( )

OUTPUT: OUTPUT:
Python is interactive language. It is case sensitive Python is
language.
It makes the difference between uppercase and
lowercase letters.
It is official language of google.

Example-2: using readline( ) function:


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.readline( )
print(str)
fin.close( )
OUTPUT:
Python is interactive language. It is case sensitive language.

Example-3: using readlines( ) function:


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.readlines( )
print(str)
fin.close( )
OUTPUT:
['Python is interactive language. It is case sensitive language.\n', 'It makes the difference
between uppercase and lowercase letters.\n', 'It is official language of google.']
Page 16
 
Some important programs related to read data from text files:
Program-a: Count the number of characters from a file. (Don’t count white spaces)
fin=open("Book.txt",'r')
str=fin.read()
L=str.split()
count_char=0
for i in L:
count_char=count_char+len(i)
print(count_char)
fin.close( )

Program-b: Count the number of words in a file.


fin=open("Book.txt",'r')
str=fin.read()
L=str.split()
count_words=0
for i in L:
count_words=count_words+1
print(count_words)
fin.close( )

Program-c: Count number of lines in a text file.


fin=open("Book.txt",'r')
str=fin.readlines()
count_line=0
for i in str:
count_line=count_line+1
print(count_line)
fin.close( )

Program-d: Count number of vowels in a text file.


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read()
Page 17
count=0
for i in str:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1
print(count)
fin.close( )

Program-e : Count the number of ‘is’ word in a text file.

fin=open("D:\\python programs\\Book.txt",'r')

str=fin.read()

L=str.split()

count=0

for i in L:

if i=='is':

count=count+1

print(count)

fin.close( )

b. Write data to a file:


There are 2 types of functions to write the data to a file.

 write( ):Write the data to a file. Syntax:

write(string) (for text files)

write(byte_string) (for binary files)


 
writelines( ): Write all strings in a list L as lines to file.

To write the data to an existing file, you have to use the following mode:

"w" - Write - will overwrite any existing content

Page 18
Example: Open the file "Book.txt" and append content to the file:
fout= open("Book.txt", "a")
fout.write("Welcome to the world of programmers")
Example: Open the file "Book.txt" and overwrite the content:
fout = open("Book.txt", "w")
fout.write("It is creative and innovative")

Program: Write a program to take the details of book from the user and write the record
in text file.
fout=open("D:\\python programs\\Book.txt",'w')
n=int(input("How many records you want to write in a file ?:"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :3
Enter details of record : 1
Enter the title of book : java
Enter price of the book: 250
Enter details of record : 2
Enter the title of book : c++
Enter price of the book: 300
Enter details of record : 3
Enter the title of book : python
Enter price of the book: 450
c. Append the data to a file:
This operation is used to add the data in the end of the file. It doesn’t overwrite the existing
data in a file. To write the data in the end of the file, you have to use the following mode:

Page 19
"a" - Append - will append to the end of the file.

Program: Write a program to take the details of book from the user and write the record
in the end of the text file.
fout=open("D:\\python programs\\Book.txt",'a')
n=int(input("How many records you want to write in a file ?
:")) for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )

OUTPUT:
How many records you want to write in a file ? :2
Enter details of record : 1
Enter the title of book : DBMS
Enter price of the book: 350
Enter details of record : 2
Enter the title of book : Computer
Networking
Enter price of the book: 360

d. Delete a file: To delete a file, you have to import the os module, and use remove( )
function.
import os
os.remove("Book.txt")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
Check if file exists, then delete it:

Page 20
import os
if os.path.exists("Book.txt"):
os.remove("Book.txt")
else:
print("The file does not exist")

3.6 WORKING WITH BINARY FILES:


Binary files store data in the binary format (0’s and 1’s) which is understandable by the
machine. So when we open the binary file in our machine, it decodes the data and displays in a
human-readable format.

(a) Write data to a Binary File:


Example:
fout=open("story.dat","wb") # open file in write and binary mode
Norml_str= "Once upon a time"
encoded_str= Norml_str.encode ("ASCII") # encoding normal text
fout.write(encoded_str) # Write data in file
fout.close( )

Output:

(b) Read the data from Binary


File: Example:
fin=open("story.dat","rb") # open file in read and binary mode
str1= fin.read() # read the data from file
decoded_str=str1.decode("ASCII") # decode the binary data
print(decoded_str)
fin.close( )

Page 21
Output:
Once upon a time

3.7 tell( ) and seek( ) methods:


 
 tell( ): It returns the current position of cursor in file.

 Example:
fout=open("story.txt","w")
fout.write("Welcome
Python") print(fout.tell( ))

fout.close( )

Output: 14

 
seek(offset) : Change the cursor position by bytes as specified by the offset.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )

Output: 5
3.8 File I/O Attributes

Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
encoding Returns the encoding format of the file
closed Returns True if the file closed else returns False

Page 22
Example:
f = open("D:\\story.txt", "r")
print("Name of the File: ", f.name)
print("File-Mode : ", f.mode)
print("File encoding format : ", f.encoding)
print("Is File closed? ", f.closed)
f.close()
print("Is File closed? ", f.closed)

OUTPUT:
Name of the File: D:\story.txt
File-Mode : r
File encoding format : cp1252
Is File closed? False
Is File closed? True
DATA STRUCTURE-I (LINEAR LIST)
7.1 INTRODUCTION:
Definition: The logical or mathematical model of a particular organization of data is called
data structure. It is a way of storing, accessing, manipulating data.

7.2 TYPES OF DATA STRUCTURE:


There are two types of data structure:
1. Linear data structure
2. Non-Linear data structure

DATA STRUCTURE

LINEAR DATA NON-LINEAR


STRUCTURE DATA STRUCTURE

LINKED
ARRAY STACK QUEUE TREE GRAPH
LIST

Fig: Types of data structure

1. Linear data structure: It is simple data structure. The elements in this data structure creates
a sequence. Example: Array, linked list, stack, queue.
2. Non-Linear data structure: The data is not in sequential form. These are multilevel data
structures. Example: Tree, graph.

Page 45
7.3 OPERATION ON DATA STRUCTURE:
There are various types of operations can be performed with data structure:
1. Traversing: Accessing each record exactly once.
2. Insertion: Adding a new element to the structure.
3. Deletion: Removing element from the structure.
4. Searching: Search the element in a structure.
5. Sorting: Arrange the elements in ascending and descending order.
6. Merging: Joining two data structures of same type. (not covered in syllabus)

7.4 ARRAY (LISTS) IN DATA STRUCTURE:


An array or list is the collection of elements in ordered way. There are two types of arrays:
1. One dimensional array (1-D Lists)
2. Multi-dimensional array (Nested Lists)

7.4.1. One Dimensional array: It is the collection of homogeneous elements in an order.


a. Traversing 1-D array (List):
L=[10,20,30,40,50]
n=len(L)
for i in range(n):
print(L[i])

Output:
10
20
30
40
50
b. Inserting Element in a list: There are two ways to insert an element in a list:
(i) If the array is not sorted
(ii) If the array is sorted

Page 46
(i) If the array is not sorted: In this case, enter the element at any position using insert(
) function or add the element in the last of the array using append( ) function.
Example:
L=[15,8,25,45,13,19]
L.insert(3, 88) # insert element at the index 3
print(L)
Output:
[15, 8, 25, 88, 45, 13, 19]

(ii) If the array is sorted: In this case, import bisect module and use the functions bisect( )
and insort( ).
bisect( ) : identifies the correct index for the element and returns the
index. insort( ): Inserts the element in the list in its correct order.
Example:
import bisect
L=[10,20,30,40,50]
print("Array before insertion the element:", L)
item=int(input("Enter the element to insert in array: "))
pos=bisect.bisect(L,item) #will return the correct index for item
bisect.insort(L,item) #will insert the element
print("Element inserted at index: ", pos)
print("Array after insertion the element : ", L)

OUTPUT:
Array before insertion the value: [10, 20, 30, 40, 50]
Enter the element to insert in array: 35
Element inserted at index : 3
Array after insertion the element : [10, 20, 30, 35, 40, 50]
Note: bisect( ) works only with that lists which are arranged in ascending order.

Page 47
c. Deletion of an element from a List: To delete an element from a list we can use remove( )
or pop( ) method.
Example:
L=[10,15,35,12,38,74,12]
print("List Before deletion of element: ", L)
val=int(input("Enter the element that you want to delete: "))
L.remove(val)
print("After deletion the element", val,"the list is: ", L)

OUTPUT:
List Before deletion of element: [10, 15, 35, 12, 38, 74, 12]
Enter the element that you want to delete: 12
After deletion the element 12 the list is: [10, 15, 35, 38, 74, 12]

d. Searching in a List:
There are two types of searching techniques we can use to search an element in a list. These
are:
(i) Linear Search
(ii) Binary Search

(i) Linear Search: It is a simple searching technique.


Program:
L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)

Page 48
break
else:
print("Element not Found")

Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4

(ii) Binary Search: (Theory already discussed in the chapter recursion).


Program:
def BinarySearch(LIST,n,item):
LB=0
UB=n-1
while LB<=UB:
mid=int((LB+UB)/2)
if item<LIST[mid]:
UB=mid-1
elif item>LIST[mid]:
LB=mid+1
else: return
mid
else:
return-1
L=eval(input("Enter the elements in sorted order:"))
size=len(L)
element=int(input("Enter the element that you want to search:"))
found=BinarySearch(L,size,element)

Page 49
if found>=0:
print(element, "Found at the position : ",found+1)
else:
print("Element not present in the list")

OUTPUT:
Enter the elements in sorted order: [12,23,31,48,51,61,74,85]
Enter the element that you want to search : 61
61 Found at the position : 6

Linear Search Vs Binary Search:


Linear Search Binary Search
Access of elements sequentially. Access of elements randomly.
Elements must be in sorted order i.e. ascending
Elements may or may not be in sorted order.
or descending order
Takes more time to search an element. Takes less time to search an element.
easy tricky
Efficient for small array. Efficient for larger array

e. Sorting: To arrange the elements in ascending or descending order. There are many
sorting techniques. Here we shall discuss two sorting techniques:
(i) Bubble sort
(ii) Insertion sort

(i) BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons,
in which each element is compared to its adjacent element and the elements are swapped if
they are not in proper order.

Page 50
PROGRAM:

L=eval(input("Enter the elements:"))

n=len(L)

for p in range(0,n-1):

for i in range(0,n-1):

if L[i]>L[i+1]:

L[i], L[i+1] = L[i+1],L[i]

print("The sorted list is : ", L)

OUTPUT:

Enter the elements:[60, 24, 8, 90, 45, 87, 12, 77]

The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
Page 51
(ii) INSERTION SORT: Sorts the elements by shifting them one by one and inserting the
element at right position.

PROGRAM:

L=eval(input("Enter the elements: "))

n=len(L)

for j in range(1,n):

temp=L[j]

prev=j-1

while prev>=0 and L[prev]>temp: # comparison the elements

L[prev+1]=L[prev] # shift the element forward

prev=prev-1

L[prev+1]=temp #inserting the element at proper position

print("The sorted list is :",L)


Page 52
OUTPUT:

Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]

The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]

7.4.2. Multi-Dimensional array (Nested Lists): A list can also hold another list as its element.
It is known as multi-dimensional or nested list.
A list in another list considered as an element.
Example:
>>>NL=[10, 20, [30,40], [50,60,70], 80]
>>> len(NL)
5
>>>secondlist=[1,2,3,[4,5,[6,7,8],9],10,11]
>>> len(secondlist)
6

Accessing the elements from nested list:


Example-1:
>>> L=[1, 2, 3, [4, 5, [ 6, 7, 8 ], 9 ] ,10, 11]
>>> L[1]
2
>>> L[3]
[4, 5, [6, 7, 8], 9]
>>> L[3][1]
5
>>> L[3][2][0]
6
>>> L[3][2]
[6, 7, 8]
>>> L[3][2][1]
Page 53
7
>>> L[3][3]
9

Example-2:
>>> L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"]
>>> L[0][0]
'P'
>>> L[3][0][2]
'd'
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range

Page 54
CHAPTER-8
DATA STRUCTURE-II (STACK AND QUEUE)
8.1 STACK IN PYTHON:
8.1.1 INTRODUCTION:

  Stack is a linear data structure.


 Stack is a list of elements in which an element may be inserted or deleted only at
 one end, called the TOP of the stack.
  It follows the principle Last In First Out (LIFO).
 There are two basic operations associated with stack:
o Push : Insert the element in stack o
Pop : Delete the element from stack

Example: Stack Push and Pop operations

8.1.2 MENU BASED PROGRAMME FOR STACK:


class Stack:
def __init__(self):
self.items = [ ]

def isEmpty(self): # Checks whether the stack is empty or not


return self.items == [ ]

def push(self, item): #Insert an element


self.items.append(item)

def pop(self): # Delete an element


return self.items.pop( )

def peek(self): #Check the value of top return


self.items[len(self.items)-1]

def size(self): # Size of the stack i.e. total no. of elements in stack
return len(self.items)

s = Stack( )
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")

choice=int(input("Enter your choice (1-5) : "))

if choice==1:
val=input("Enter the element: ")
s.push(val)
elif choice==2:
if s.items==[ ]:
print("Stack is empty")
else:
print("Deleted element is :", s.pop( ))
elif choice==3:
print(s.items)
elif choice==4:
print("Size of the stack is :", s.size( ))
elif choice==5:
print("Value of top element is :", s.peek( ))
else:
print("You enetered wrong choice ")

Page 56
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
var=True
else:
var=False

8.1.3 STACK POLISH NOTATION:


To evaluate an expression, we use three types of polish notations:
1. Prefix notation : +AB
2. Infix notation :A+B
3. Postfix notation : AB+
The evaluation of expression depends upon order of the element and precedence
of an operator.

Precedence of Basic Arithmetic operators:


Precedence
Name of operator Symbol (Highest to
Lowest)

Exponentiation ↑ 1

Multiplication, division, division


floor and modulus *, /, //, % 2

Addition and Subtraction +, - 3

8.1.4 Evaluation of an expression written in postfix notation:


Example-1: Evaluate the following expression:
P: 5 , 6, 2, +, *, 12, 4, /, -
Solution:

Page 57
Element Operation Stack Result
5 Push 5
6 Push 5, 6
2 Push 5, 6, 2
+ Pop 5, 8 6+2=8
* Pop 40 5*8=40
12 Push 40, 12
4 Push 40, 12, 4
/ Pop 40, 3 12/4=3
- Pop 37 40-3=37

Example-2: Evaluate the following expression:


P: 4 , 5, +, 6, 11, -, *,15, /
Solution:
Element Operation Stack Result
4 Push 4
5 Push 4, 5
+ Pop 9 4+5=9
6 Push 9, 6
11 Push 9, 6, 11
- Pop 9, -5 6-11= -5
* Pop -45 9* -5 = -45
15 Push -45, 15
/ Pop -45/15 -45/15 = -3

Example-3: Evaluate the following expression:


P: True, False, True, OR, False, AND, NOT, OR
Solution:
Element Operation Stack Result
True Push True
False Push True, False
True Push True, False, True
OR Pop True, True False OR True= True
False Push True, True, False
AND Pop True, False True AND False= False
NOT True, True NOT False = True
OR Pop True True OR True = True

Page 58
8.1.5 Infix to Postfix Conversion:
Example-1 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A + B * ( C-D ) / E )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element in expression
+ (+ A Operator, so push into stack
B (+ AB Move the element in expression
* (+* AB Operator, push into stack, * has higher precedence than
+, so can come after +
( (+*( AB Push the open parentheses symbol into stack
C (+*( ABC Move the element in expression
- (+*(- ABC Operator, push into stack
D (+*(- ABCD Move the element in expression
) (+* ABCD - Closing parentheses, so pop the elements of the stack up
to opening parentheses
/ (+/ ABCD - * Operator, / and * operators have the same precedence,
so associativity from left to write will take place and *
will pop from stack and / will push into stack
E (+/ ABCD - *E Move the element in expression
) ABCD - * E / + Closing parentheses, so pop the elements of the stack up
to opening parentheses

Example-2 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A / B - ( C*D ↑ E ) + F )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element into expression
/ (/ A Operator, so push into stack
B (/ AB Move the element into expression
- (- AB/ Operator, - has lower precedence than /. so, / will pop
from stack and – will push into stack.
( (-( AB/ Push the symbol into stack
C (-( AB/C Move the element into expression
* (-(* AB/C Operator, push into stack
D (-(* AB/CD Move the element into expression
↑ ( - ( *↑ AB/CD Operator, ↑ has higher precedence than *, so can come
after *.
E ( - ( *↑ AB/CDE Move the element into expression

Page 59
) (- AB/CDE↑ * Closing parentheses, so pop the elements of the stack up
to opening parentheses
+ (+ AB/CDE↑ * - Operator, - and + both have same precedence, to
associativity from left to right take place. – will pop
from stack then + will push into stack.
F (+ AB/CDE↑ * - F Move the element into expression

) AB/CDE↑ * - F + Closing parentheses, so pop the elements of the stack up


to opening parentheses

Page 65

You might also like