Professional Documents
Culture Documents
PDS LAB Manual
PDS LAB Manual
Theory:
Python is a language with a simple syntax, and a powerful set of libraries. It is an interpreted
language, with a rich programming environment, including a robust debugger and profiler.
While it is easy for beginners to learn, it is widely used in many scientific areas for data
exploration. We cover data types, control flow, object-oriented programming, and graphical
user interface-driven applications. The examples and problems used in this course are drawn
from diverse areas such as text processing, simple graphics creation and image manipulation,
HTML and web programming, and genomics.
1. Learn basic programming constructs –data types, decision structures, control structures
in python.
2. Know how to use libraries for string manipulation and user-defined functions.
3. Learn to use in-built data structures in python – Lists, Tuples, Dictionary and File
handling.
4. Learn the fundamental principles of Object-Oriented Programming.
5. Solve problems through application of OO concepts and using Files/database.
Using IDLE
IDLE is the standard Python development environment. Its name is an acronym of "Integrated
DeveLopment Environment". It works well on both Unix and Windows platforms.
It has a Python shell window, which gives you access to the Python interactive mode. It also
has a file editor that lets you create and edit existing Python source files.
During the following discussion of IDLE's features, instead of passively reading along, you
should start IDLE and try to replicate the screenshots.
When you start up IDLE, a window with an interactive Python shell will pop up:
hello world
Try typing an underscore ( _). Can you see it? On some operating systems, the bottoms of
hanging letters such as 'g' or 'y', as well as underscores, cannot be seen in IDLE. If this is the
case for you, go to Options -> Configure IDLE, and change the size of the default font to 9 or
11. This will fix the problem!
>>> 4+4
8
>>> 8**3
512
Addition (+), subtraction (-), multiplication (*), division (/), modulo (%) and power (**)
operators are built into the Python language. This means you can use them right away. If you
want to use a square root in your calculation, you can either raise something to the power of
0.5 or you can import the math module. Below are two examples of square root calculation:
>>> 16**0.5
4.0
>>> import math
>>> math.sqrt(16)
4.0
Gandhinagar Institute of Technology 3150713 PDS
The math module allows you to do a number of useful operations:
>>> math.log(16, 2)
4.0
>>> math.cos( 0 )
1.0
Note that you only need to execute the import command once after you start IDLE; however,
you will need to execute it again if you restart the shell, as restarting resets everything back to
how it was when you opened IDLE. Creating scripts
Exercises:
1. Program to calculate area of a triangle:
a. Given Base and height of the triangle. Take input from user.
b. Given Three sides of a triangle (Make sure that it forms a triangle). Take input
from user.
Theory:
As we can see the function accepts a single parameter and is used to return the identity of an
object. This identity has to be unique and constant for this object during the lifetime.
Two objects with non-overlapping lifetimes may have the same id() value. If we relate this to
C, then they are actually the memory address, here in Python it is the unique id. This function
is generally used internally in Python.
Examples:
The output is the identity of the object passed. This is random but when running in the
same program, it generates unique and same identity.
Input:
id(1025)
Output: 2698213093488
Output varies with different runs
Input :
id("geek")
Output: 2698213126704
str2 = "geek"
print(id(str2))
# Use in Lists
list1 = ["aakash", "priya", "abdul"]
print(id(list1[0]))
Gandhinagar Institute of Technology 3150713 PDS
print(id(list1[2]))
The id() function returns identity of the object. This is an integer which is unique for the given
object and remains constant during its lifetime.
Example:
print('id of 5 =',id(5))
a = 5
print('id of a =',id(a))
b = a
print('id of b =',id(b))
c = 5.0
print('id of c =',id(c))
Python have a built-in method called as type which generally come in handy while figuring
out the type of variable used in the program in the runtime.
The type function returns the datatype of any arbitrary object. The possible types are listed
in the types module. This is useful for helper functions that can handle several types of
data.
>>> type(1)
<class 'int'>
>>> li = []
>>> type(li)
<class 'list'>
>>> import odbc
>>> type(odbc)
<class 'module'>
>>> import types
>>> type(odbc) == types.ModuleType
True
Type takes anything -- and I mean anything -- and returns its data type. Integers, strings, lists,
dictionaries, tuples, functions, classes, modules, even types are acceptable.
Gandhinagar Institute of Technology 3150713 PDS
• type can take a variable and return its datatype.
• type also works on modules.
You can use the constants in the types module to compare types of objects. This is what the
info function does, as you'll see shortly.
Exercises:
1. Write a output of following code.
# Python id() function example
l1 = [1,2,3,4]
l2 = [1,2,3,4]
l3 = [3,5,6,7]
# Calling function
id1 = id(l1)
id2 = id(l2)
id3 = id(l3)
# Displaying result
print((l1==l2),(l1==l3))
# Objects with the same values can have different ids
print((id1==id2),(id1==id3))
# l1 and l2 returns True, while id1 and id2 returns False
Review Questions:
1. What data types are used in Python?
2. What is the difference between functions used in python and C? Are both the same?
Theory:
Prime numbers: A prime number is a natural number greater than 1 and having no positive
divisor other than 1 and itself.
Composite number: Other natural numbers that are not prime numbers are called composite
numbers.
Here is source code of the Python Program to check if a number is a prime number.
Exercises:
1. Write a python program for composite numbers.
Review Questions:
1. Why don’t we use semi colon in this program?
2. What are Composite numbers?
Theory:
The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13,
21, 34, 55, 89, 144, ……..
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0
and 1. All other terms are obtained by adding the preceding two terms. This means to say the
nth term is the sum of (n-1)th and (n-2)th term. In mathematical terms, the sequence Fn of
Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2 with initial value F0 = 0 and F1 = 1
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Review Questions:
1. What is the difference between iteration and recursion?
2. How looping technique is different from Recursion?
Theory:
Like other programming languages, it’s possible to access individual characters of a string by
using array-like indexing syntax. In this we can access each and every element of string through
their index number and the indexing starts from 0. Python does index out of bound checking.
Example:
We use the slice notation on strings. In this example, we omit the first index to start at the
beginning, and then consume four characters total. We extract the first four letters.
word = "something"
Copy with slicing, we can copy sequences like lists. We assign a new list variable to a slice
with no specified start or stop values. So the slice copies the entire list and returns it.
To extract substring from the whole string then we use the syntax like
end denotes the end index of string which is not inclusive, steps denote the distance between
the two words. o beginning represents the starting index of string
Exercises:
1. Accept a string from the user and display the string with first character of each word
Capital. (Without using inbuilt function)
2. Write a program to accept a string from the user and display n characters from the left
of the string. (Accept n from the user)
3. Write a program to reverse the string using slicing.
4. Write a program to accept a string from the user and display n characters from the
right of the string. (Accept n from the user)
5. Accept a String from the user and display first two characters of each word in same
line separated by space.
Review Questions:
Theory:
To add 'ing' at the end of a given string (length should be at least 3). If the given string already
ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave
it unchanged.
To get a string from a given string where all occurrences of its first char have been changed
to '$', except the first char itself.
Python Code:
def add_string(str1):
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
b. PYTHON CODE:
def change_char(str1):
char = str1[0]
length = len(str1)
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
return str1
print(change_char('restart'))
Review Questions:
1. What are the built-in type does python provides?
2. In Python what are iterators?
Aim: To compute the input. The frequency of the words from the output should output after
sorting the key alphanumerically.
Theory:
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:
Output:
Code:
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
Output:
String H E L L O W O R L D
Positive index 0 1 2 3 4 5 6 7 8 9
• string[a]: Returns a character from a positive index a of the string from the left side as
displayed in the index graph above.
• string[-a]: Returns a character from a negative index a of the string from the right
side as displayed in the index graph above.
• string[a:b]: Returns characters from positive index a to positive index b of the as
displayed in index graph above.
• string[a:-b]: Returns characters from positive index a to the negative index b of the
string as displayed in the index graph above.
Gandhinagar Institute of Technology 3150713 PDS
• string[a:]: Returns characters from positive index a to the end of the string.
• string[:b] Returns characters from the start of the string to the positive index b.
• string[-a:]: Returns characters from negative index a to the end of the string.
• string[:-b]: Returns characters from the start of the string to the negative index b.
• string[::-1]: Returns a string with reverse order.
Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Output:
• “==” operator returns Boolean True if two strings are the same and return Boolean False
if two strings are not the same.
• “!=” operator returns Boolean True if two strings are not the same and return Boolean
False if two strings are the same.
These operators are mainly used along with if condition to compare two strings where the
decision is to be taken based on string comparison.
Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
• “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is
not in the string.
• “a” not in the string: Returns boolean True if “a” is not in the string and returns False
if “a” is in the string.
A membership operator is also useful to find whether a specific substring is part of a given
string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)
Output:
Code:
string = "Hello world I am from \"India\""
print(string)
Output:
Operator Description
%c Character
%s String
Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
Gandhinagar Institute of Technology 3150713 PDS
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:
Exercises:
1. Write a python program to get the input from user console and find the frequency of
words in input and print in sorted order.
2. Write a program that accepts a comma separated sequence of words as input and
prints the words in a comma-separated sequence after sorting them alphabetically.
Review Questions:
1. Define string operations.
2. What is concatenation function?
Theory: Python has a number of built-in data structures, including lists. Data structures provide
us with a way to organize and store data, and we can use built-in methods to retrieve or
manipulate that data.
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
Output:
The index of e: 1
The index of i: 2
Output:
The index of e: 1
The index of i: 6
Traceback (most recent call last):
File "*lt;string>", line 13, in
ValueError: 'i' is not in list
append() Parameters
Output
Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']
Output
Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]
It is important to notice that, a single item (wild_animals list) is added to the animals list in
the above program.
If you need to add items of a list to another list (rather than the list itself), use the extend()
method.
Here, all the elements of iterable are added to the end of list1.
extend() Parameters
As mentioned, the extend() method takes an iterable such as list, tuple, string etc.
# languages tuple
languages_tuple = ('Spanish', 'Portuguese')
# languages set
languages_set = {'Chinese', 'Japanese'}
a = [1, 2]
b = [3, 4]
a += b # a = a + b
# Output: [1, 2, 3, 4]
print('a =', a)
Output
a = [1, 2, 3, 4]
# Output: [1, 2, 3, 4]
print('a =', a)
Output
a = [1, 2, 3, 4]
# a1 = [1, 2, 3, 4]
a1.extend(b)
print(a1)
Here, elem is inserted to the list at the ith index. All the elements after elem are shifted to the
right.
insert() Parameters
The insert() method takes two parameters:
index - the index where the element needs to be inserted
element - this is the element to be inserted in the list
Notes:
If index is 0, the element is inserted at the beginning of the list.
If index is 3, the index of the inserted element will be 3 (4th element in the list).
# number tuple
number_tuple = (3, 4)
remove() Parameters
The remove() method takes a single element as an argument and removes it from the list.
If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.
# 'rabbit' is removed
animals.remove('rabbit')
# 'dog' is removed
animals.remove('dog')
Here, only the first occurrence of element 'dog' is removed from the list.
count() Parameters
The count() method takes a single argument:
element - the element to be counted
# print count
print('The count of i is:', count)
# print count
print('The count of p is:', count)
Output
The count of i is: 2
The count of p is: 0
# print count
print("The count of ('a', 'b') is:", count)
# print count
print("The count of [3, 4] is:", count)
Output
The count of ('a', 'b') is: 2
The count of [3, 4] is: 1
pop() parameters
• The pop() method takes a single argument (index).
• The argument passed to the method is optional. If not passed, the default index -1 is
passed as an argument (index of the last item).
• If the index passed to the method is not in range, it throws IndexError: pop index
out of range exception.
# Updated List
print('Updated List:', languages)
Output
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']
If you need to pop the 4th element, you need to pass 3 to the pop() method.
When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']
Gandhinagar Institute of Technology 3150713 PDS
When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']
If you need to remove the given item from the list, you can to use the remove() method.
And, you can use the del statement to remove an item or slices from the list.
reverse() parameter
The reverse() method doesn't take any arguments.
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
Output
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']
# Reversing a list
#Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]
# updated list
print('Updated List:', reversed_list)
Output
Gandhinagar Institute of Technology 3150713 PDS
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']
Alternatively, you can also use Python's built-in sorted() function for the same purpose.
sorted(list, key=..., reverse=...)
Note: The simplest difference between sort() and sorted() is: sort() changes the list directly
and doesn't return any value, while sorted() doesn't change the list and returns the sorted list.
sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has two optional
parameters:
• reverse - If True, the sorted list is reversed (or sorted in Descending order)
• key - function that serves as a key for the sort comparison
# print vowels
Output
Sorted list: ['a', 'e', 'i', 'o', 'u']
# print vowels
print('Sorted list (in Descending):', vowels)
Output
Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']
sorted(list, key=len)
Here, len is the Python's in-built function to count the length of an element.
The list is sorted based on the length of each element, from lowest count to highest.
We know that a tuple is sorted using its first parameter by default. Let's look at how to
customize the sort() method to sort using the second element.
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
Let's take another example. Suppose we have a list of information about the employees of an
office where each element is a dictionary.
We can sort the list in the following way:
# sorting using custom key
employees = [
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]
def get_age(employee):
return employee.get('age')
def get_salary(employee):
return employee.get('salary')
[{'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Alan Turing', 'age': 25, 'salary':
10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'Mikhail Tal', 'age': 40,
'salary': 15000}]
For the second case, age (int) is returned and is sorted in ascending order.
For the third case, the function returns the salary (int), and is sorted in the descending order
using reverse = True.
It is a good practice to use the lambda function when the function can be summarized in one
line. So, we can also write the above program as:
# sorting using custom key
employees = [
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]
[{'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Alan Turing', 'age': 25, 'salary':
10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'Mikhail Tal', 'age': 40,
'salary': 15000}]
[{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, {'Name': 'Alan Turing', 'age': 25, 'salary':
10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'John Hopkins', 'age': 18,
'salary': 1000}]
The problem with copying lists in this way is that if you modify new_list, old_list is also
modified. It is because the new list is referencing or pointing to the same old_list object.
old_list = [1, 2, 3]
new_list = old_list
However, if you need the original list unchanged when the new list is modified, you can use
the copy() method.
copy() parameters
The copy() method doesn't take any parameters.
Return Value from copy()
The copy() method returns a new list. It doesn't modify the original list.
# copying a list
new_list = my_list.copy()
Output
Copied List: ['cat', 0, 6.7]
If you modify the new_list in the above example, my_list will not be modified.
Output
Old List: ['cat', 0, 6.7]
New List: ['cat', 0, 6.7, 'dog']
clear() Parameters
The clear() method doesn't take any parameters.
print('List:', list)
Output
List: []
Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method.
You can use the del operator instead.
Exercises:
1. Concatenate two lists index-wise.
2. Given a Python list of numbers. Turn every item of a list into its square
3. Remove empty strings from the list of strings.
4. Given a nested list extend it by adding the sub list ["h", "i", "j"] in such a way that it
will look like the following list.
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
Expected List:
list1= ['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']
5. Given a Python list, find value 20 in the list, and if it is present, replace it with 200.
Only update the first occurrence of a value.
list1 = [5, 10, 15, 20, 25, 50, 20]
6. Given a Python list, remove all occurrence of 20 from the list.
list1 = [5, 10, 15, 20, 25, 50, 20]
Review Questions:
1. How do you remove duplicates froma list?
2. How To Determine The Size Of Your List in Python?
Theory: In Python programming, a tuple is similar to a list. The differences 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.
Python Tuple
In this article, you'll learn everything about Python tuples. More specifically, what are tuples,
how to create them, when to use them and various methods you should be familiar with. A
tuple in Python 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 we can change the elements of a list.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.A tuple can
have any number of items and they may be of different types (integer, float, list, string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
print(a) #3
print(b) # 4.6
print(c) # dog
Output
Having one element within parentheses is not enough. We will need a trailing comma to
indicate that it is, in fact, a tuple.
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
Output
p
t
s
4
2. Negative Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Output
t
p
Output
Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need the index that will slice the portion from the
tuple.
Changing a Tuple
Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once
they have been assigned. But, if the element is itself a mutable data type like a list, its nested
items can be changed.
We can also assign a tuple to different values (reassignment).
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
# Output: ('g', 'a', 'n', 'd', 'h', 'i', 'n', 'a', 'g',’a’,’r’)
print(my_tuple)
Output
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Output
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete
or remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples
my_tuple = ('g', 'a', 'n', 'd', 'h', 'i', 'n', 'a', 'g', ’a’, ’r’)
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two
methods are available.
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
Output
2
3
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
Output
True
False
True
Hello John
Hello Kate
Exercises:
1. Reverse the following tuple
aTuple = (10, 20, 30, 40, 50)
2. Access value 20 from the following tuple
aTuple = ("Orange", [10, 20, 30], (5, 15, 25))
3. Unpack the following tuple into 4 variables.
aTuple = (10, 20, 30, 40)
4. Swap the following two tuples
tuple1 = (11, 22)
tuple2 = (99, 88)
5. Modify the first item (22) of a list inside a following tuple to 222
tuple1 = (11, [22, 33], 44, 55)
Review Questions:
1. What is a tuple?
2. Differentiate between a tuple and a list?
Theory:
A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This
means the last element inserted inside the stack is removed first. You can think of the stack
data structure as the pile of plates on top of another.
Here, you can:
Put a new plate on top
Remove the top plate
And, if you want the plate at the bottom, you must first remove all the plates on top. This is
exactly how the stack data structure works.
In the above image, although item 2 was kept last, it was removed first. This is exactly how
the LIFO (Last In First Out) Principle works.We can implement a stack in any programming
language like C, C++, Java, Python or C#, but the specification is pretty much the same.
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
Output:
pushed item: 1
pushed item: 2
pushed item: 3
pushed item: 4
popped item: 4
stack after popping an element: ['1', '2', '3']
To reverse a word - Put all the letters in a stack and pop them out. Because of the LIFO order
of stack, you will get the letters in reverse order.
In compilers - Compilers use the stack to calculate the value of expressions like 2 + 4 / 5 * (7
- 9) by converting the expression to prefix or postfix form.
In browsers - The back button in a browser saves all the URLs you have visited previously in
a stack. Each time you visit a new page, it is added on top of the stack. When you press the
back button, the current URL is removed from the stack, and the previous URL is accessed.
In the above image, since 1 was kept in the queue before 2, it is the first to be removed from
the queue as well. It follows the FIFO rule. In programming terms, putting items in the queue
is called enqueue, and removing items from the queue is called dequeue. We can implement
the queue in any programming language like C, C++, Java, Python or C#, but the specification
is pretty much the same.
Working of Queue
Queue operations work as follows:
• two pointers FRONT and REAR
• FRONT track the first element of the queue
• REAR track the last element of the queue
• initially, set value of FRONT and REAR to -1
Enqueue Operation
• check if the queue is full
• for the first element, set the value of FRONT to 0
• increase the REAR index by 1
• add the new element in the position pointed to by REAR
Dequeue Operation
• check if the queue is empty
• return the value pointed by FRONT
• increase the FRONT index by 1
• for the last element, reset the values of FRONT and REAR to -1
class Queue:
def __init__(self):
self.queue = []
# Add an element
def enqueue(self, item):
self.queue.append(item)
# Remove an element
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def size(self):
return len(self.queue)
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
Output:
[1, 2, 3, 4, 5]
After removing an element
[2, 3, 4, 5]
Limitations of Queue
As you can see in the image below, after a bit of enqueuing and dequeuing, the size of the
queue has been reduced.
Complexity Analysis
The complexity of enqueue and dequeue operations in a queue using an array is O(1). If you
use pop(N) in python code, then the complexity might be O(n) depending on the position of
the item to be popped.
Applications of Queue
• CPU scheduling, Disk Scheduling
• When data is transferred asynchronously between two processes. The queue is used for
synchronization. For example: IO Buffers, pipes, file IO, etc
• Handling of interrupts in real-time systems.
• Call Center phone systems use Queues to hold people calling them in order.
Exercises:
1. Circular Queue implementation in Python.
2. Priority Queue implementation in Python.
3. Deque implementation in python.
4. Write a Python program to insert items into a list in sorted order.
Expected Output:
Original List:
[25, 45, 36, 47, 69, 48, 68, 78, 14, 36]
Sorted List:
[14, 25, 36, 36, 45, 47, 48, 68, 69, 78]
5. Write a Python program to find whether a queue is empty or not.
Review Questions:
1. What is Stack and how implementation of Stack in c is different from python?
2. Difference between queue and stack?