Data Structures Using Python 1737761630
Data Structures Using Python 1737761630
INDEX
3 I Operators in Python 21
6 II Arrays in Python 42
7 III Functions 45
10 IV Lists 61
11 IV Tuples 68
12 IV Dictionaries 73
13 V Sorting Techniques 76
14 V Linked Lists 79
15 V Stacks 84
16 V Queues 86
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Unit-I
Definition:
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.
Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL andPHP.
Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write yourprograms.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code withinobjects.
Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers togames.
History of Python
Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for
Mathematics and Computer Science in theNetherlands.
Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other
scriptinglanguages.
At the time when he began implementing Python, Guido van Rossum was also reading
the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from
the seventies, in the unlikely case you didn't know). It occurred to him that he needed a
name that was short, unique, and slightly mysterious, so he decided to call the language
Python.
Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing itsprogress.
Python 1.0 was released on 20 February,1991.
Python 2.0 was released on 16 October 2000 and had many major new features,
including a cycle detecting garbage collector and support for Unicode. With this release
the development process was changed and became more transparent and community-
backed.
Python 3.0 (which early in its development was commonly referred to as Python 3000 or
py3k), a major, backwards-incompatible release, was released on 3 December 2008 after
a long period of testing. Many of its major features have been back ported to the
DARA STRUCTURES USING PYTHON Page 1
backwards-compatible Python 2.6.x and 2.7.x versionseries.
In January 2017 Google announced work on a Python 2.7 to go transcompiler, which The
Register speculated was in response to Python 2.7's plannedend-of-life.
Python Features:
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the languagequickly.
Easy-to-read: Python code is more clearly defined and visible to theeyes.
Easy-to-maintain: Python's source code is fairlyeasy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, andMacintosh.
Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets ofcode.
Portable: Python can run on a wide variety of hardware platforms and has the same
interface on allplatforms.
Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be moreefficient.
Databases: Python provides interfaces to all major commercialdatabases.
GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh,
and the X Window system ofUNIX.
Scalable: Python provides a better structure and support for large programs than shell
scripting.
Step 4: After installation location will be displayed. The Default location is C:\Python27.
Click on next to continue.
GotoEnvironmentVariablesandgotoSystemVariablesselectPathandclickon
Edit.
Add semicolon (;) at end and copy the location C:\Python27 and give semicolon (;) and
clickOK.
Now you can type any valid python expression at the prompt. Python reads the typed
expression, evaluates it and prints the result.
Variables:
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
KEYWORDS
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the Python keywords
INPUT Function:
To get input from the user you can use the input function. When the input function is
called the program stops running the program, prompts the user to enter something at the
keyboard by printing a string called the prompt to the screen, and then waits for the user to
press the Enter key. The user types a string of characters and presses enter. Then the input
function returns that string and Python continues running the program by executing the next
statement after the input statement.
Python provides the function input(). input has an optional parameter, which is the
prompt string.
For example,
Indentation
Code blocks are identified by indentation rather than using symbols like curly braces.
Without extra symbols, programs are easier to read. Also, indentation clearly identifies which
block of code a statement belongs to. Of course, code blocks can consist of single statements,
too. When one is new to Python, indentation may come as a surprise. Humans generally prefer
to avoid change, so perhaps after many years of coding with brace delimitation, the first
impression of using pure indentation may not be completely positive. However, recall that two
of Python's features are that it is simplistic in nature and easy toread.
Python does not support braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation. All the continuous
lines indented with same number of spaces would form a block. Python strictly follow
indentation rules to indicate the blocks.
Example:
str1="welcome"
print "Capitalize function---",str1.capitalize()
print str1.center(15,"*")
print "length is",len(str1)
print "count function---",str1.count('e',0,len(str1))
print "endswith function---",str1.endswith('me',0,len(str1))
print "startswith function---",str1.startswith('me',0,len(str1))
print "find function---",str1.find('e',0,len(str1))
str2="welcome2017"
print "isalnum function---",str2.isalnum()
print "isalpha function---",str2.isalpha()
print "islower function---",str2.islower()
print "isupper function---",str2.isupper()
[Type text] Page 19
str3=" welcome"
print "lstrip function---",str3.lstrip()
str4="77777777cse777777";
print "lstrip function---",str4.lstrip('7')
print "rstrip function---",str4.rstrip('7')
print "strip function---",str4.strip('7')
str5="welcome to java"
print "replace function---",str5.replace("java","python")
Output:
Capitalize function--- Welcome
****welcome****
length is 7
count function--- 2
endswith function--- True
startswith function--- False
find function--- 1
isalnum function--- True
isalpha function--- False
islower function--- True
isupper function--- False
lstrip function---
welcome lstrip function-
-- cse777777
rstrip function--- 77777777cse
strip function--- cse
replace function--- welcome to python
Python Boolean:
Booleans are identified by True or False.
Example:
Program:
a = True
b = False
print a
print b
Output:
True
False
Function Description
[Type text] Page 20
int(x [,base]) Converts x to an integer.
long(x [,base] ) Converts x to a long integer.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary, d must be a sequence of (key, value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Types of Operators:
Arithmetic Operators:
Some basic arithmetic operators are +, -, *, /, %, **, and //. You can apply these
operators on numbers as well as variables to perform corresponding operations.
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left hand
- Subtraction a – b = -10
operand.
* Multiplication Multiplies values on either side of the operator a * b = 200
Divides left hand operand by right hand
/ Division b/a=2
operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power) calculation on a**b =10 to
** Exponent
operators the power 20
Output:
b is big
Assignment Operators
Logical Operators
Example:
a=20
b=10
c=30
if a >= b and a >= c:
print "a isbig"
elif b >= a and b >= c:
print "b isbig"
else:
print "c is big"
Output:
c is big
Bitwise Operators
Membership Operators
Python‟s membership operators test for membership in a sequence, such as strings,
lists, or tuples.
Operator Description Example
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the left
hand side. All variables used in the expression must be assigned values before evaluation is
attempted.
Example:
a=10
b=22
c=34
x=a*b+c
y=a-b*c
z=a+b+c*c-a
print "x=",x
print "y=",y
print "z=",z
Output:
x= 254
y=-738
z= 1178
Python programming language assumes any non-zero and non-null values as True,
and if it is either zero or null, then it is assumed as Falsevalue.
Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements.
if...else statements if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.
nested if statements You can use one if or else if statement inside another if or else if
statement(s).
The if Statement
It is similar to that of other languages. The if statement contains a logical expression
using which data is compared and a decision is made based on the result of the comparison.
Example:
a=10
b=15
if a < b:
print “B is big”
print “B value is”,b
Output:
B is big
B value is 15
The if ... else statement
An else statement can be combined with an if statement. An else statement contains
the block of code that executes if the conditional expression in the if statement resolves to 0
or a FALSEvalue.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax:
if condition:
statement(s)
else:
statement(s)
Output:
A is big
A value is 48
END
Q) Write a program for checking whether the given number is even or not.
Program:
a=input("Enter a value: ")
if a%2==0:
print "a is EVEN number"
else:
print "a is NOT EVEN Number"
Output-1: Output-2:
Enter avalue: 56 Enter a value:27
a isEVENNumber a is NOT EVENNumber
Example:
a=20
b=10
c=30
if a >= b and a >= c:
print "a isbig"
elif b >= a and b >= c:
print "b isbig"
else:
print "c is big"
Output:
c is big
Decision Loops
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement:
Output-1: Output-2:
1 1
END 2
2 3
END END
3
END
The first element of the sequence is assigned to the variable written after „for‟ and
then the statements are executed. Next, the second element of the sequence is assigned to the
variable and then the statements are executed second time. In this way, for each element of
the sequence, the statements are executed once. So, the for loop is executed as many times as
there are number of elements in thesequence.
Example-3: Example-4:
name= "python" for x in range(10,0,-1):
for letter print x,
inname:
Output-3: printletter Output-4:
p 10 9 8 7 6 5 4 3 2 1
y
t
h
o
n
Output:
Enter the number: 5
Factorial is 120
Example-5:
for i in range(1,6):
for j in range(1,6):
if i==j:
print"$",
elifi==1 or j==1 or i==5 or j==5:
print"*",
else:
print " ",
print""
Example-7:
for i in range(1,6):
for j in range(1,4):
if i==2 and j==1:
print"*",
elifi==4 and j==3:
print"*",
elifi==1 or i==3 or i==5:
print"*",
else:
print " ",
print""
Example-8:
for i in range(1,6):
for j in range(1,4):
if i==1 or j==1 or i==3 or i==5:
print "*",
else:
print " ",
print""
Example-9:
for i in range(1,6):
for c in range(i,6):
print "",
for j in range(1,i+1):
print "*",
print ""
Example-10:
for i in range(1,6):
for j in range(1,i+1):
print j,
print ""
1) Write a program for print given number is prime number or not using for loop.
Program: n=input("Enter the n value")
count=0
for i in range(2,n):
if n%i==0:
count=count+1
break
if count==0:
print "Prime Number"
else:
print "Not Prime Number"
Output:
Enter n value: 17
Prime Number
2) WriteaprogramprintFibonacciseriesandsumtheevennumbers.Fibonacciseries
is 1,2,3,5,8,13,21,34,55
n=input("Enter n value ")
f0=1
f1=2
sum=f1
printf0,f1,
for i inrange(1,n-1):
f2=f0+f1
print f2,
f0=f1
f1=f2
if f2%2==0:
sum+=f2
print "\nThe sum of even Fibonacci numbers is", sum
Output:
Enter n value 10
1 2 3 5 8 13 21 34 55 89
The sum of even fibonacci numbers is 44
Output:
Enter the range: 21
1 2 3 5 7 11 13 17 19
Sum of prime numbers is 78
4) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, . . . ,1/10
Program:
for i in range(1,11):
print "Decimal Equivalent of 1/",i,"is",1/float(i)
Output:
Decimal Equivalent of 1/ 1 is 1.0
Decimal Equivalent of 1/ 2 is 0.5
Decimal Equivalent of 1/ 3 is 0.333333333333
Decimal Equivalent of 1/ 4 is 0.25
Decimal Equivalent of 1/ 5 is 0.2
Decimal Equivalent of 1/ 6 is 0.166666666667
Decimal Equivalent of 1/ 7 is 0.142857142857
Decimal Equivalent of 1/ 8 is 0.125
Decimal Equivalent of 1/ 9 is 0.111111111111
Decimal Equivalent of 1/ 10 is 0.1
9) Write a program that takes input string user and display that string if string contains
at least one Uppercase character, one Lowercase character and onedigit.
Program:
pwd=input("Enter the password:")
u=False
l=False
d=False
for i in range(0,len(pwd)):
if pwd[i].isupper():
u=True
elifpwd[i].islower():
l=True
elifpwd[i].isdigit():
d=True
if u==True and l==True and d==True:
print pwd.center(20,"*")
else:
print "Invalid Password"
Output-1:
Enter the password:"Mothi556"
******Mothi556******
Output-2:
Enter the password:"mothilal"
Invalid Password
Example:
The type code character should be written in single quotes. After that the elements
should be written in inside the square braces [ ] as
a = array ( „i‟, [4,8,-7,1,2,5,9] )
10 20 30 40 50
a[0] a[1] a[2] a[3] a[4]
Example:
from array import *
a=array('i', [10,20,30,40,50,60,70])
print "length is",len(a)
print " 1st position character", a[1]
print "Characters from 2 to 4", a[2:5]
print "Characters from 2 to end", a[2:]
print "Characters from start to 4",a[:5]
print "Characters from start to end",a[:]
Array Methods:
Method Description
a.append(x) Adds an element x at the end of the existing array a.
a.count(x) Returns the number of occurrences of x in the array a.
a.extend(x) Appends x at the end of the array a. „x‟ can be another array or
iterable object.
a.fromfile(f,n) Reads n items from from the file object f and appends at the end of
the array a.
a.fromlist(l) Appends items from the l to the end of the array. l can be any list or
iterable object.
a.fromstring(s) Appends items from string s to end of the array a.
a.index(x) Returns the position number of the first occurrence of x in the array.
Raises „ValueError‟ if not found.
a.pop(x) Removes the item x from the array a and returns it.
a.pop( ) Removes last item from the array a
a.remove(x) Removes the first occurrence of x in the array. Raises „ValueError‟
if not found.
a.reverse( ) Reverses the order of elements in the array a.
a.tofile( f ) Writes all elements to the file f.
a.tolist( ) Converts array „a‟ into a list.
a.tostring( ) Converts the array into a string.
We can return the result or output from the function using a „return‟ statement in the
function body. When a function does not return any result, we need not write the return
statement in the body of the function.
Q) Write a program to find the sum of two numbers and return the result from the
function.
def add(a,b):
"""This function sum the numbers"""
c=a+b
return c
print add(5,12) #17
print add(1.5,6)#6.5
Pass by Value:
Pass by value represents that a copy of the variable value is passed to the function and
any modifications to that value will not reflect outside the function. In python, the values are
sent to functions by means of object references. We know everything is considered as an
object in python. All numbers, strings, tuples, lists and dictionaries are objects.
If we store a value into a variable as:
x=10
In python, everything is an object. An object can be imagined as a memory block
where we can store some value. In this case, an object with the value „10‟ is created in
memoryforwhichaname„x‟isattached.So,10 istheobject and„x‟isthenameortaggiven to that
object. Also, objects are created on heap memory which is a very huge memory that depends
on the RAM of our computer system.
Example: A Python program to pass an integer to a function and modifyit.
defmodify(x):
x=15
print "inside",x,id(x)
x=10
modify(x)
print "outside",x,id(x)
Output:
inside 15 6356456
outside 10 6356516
From the output, we can understand that the value of „x‟ in the function is 15 and that is not
available outside the function. When we call the modify( ) function and pass „x‟ as:
modify(x)
We should remember that we are passing the object references to the modify( ) function. The
object is 10 and its references name is „x‟. This is being passed to the modify( ) function.
Inside the function, we are using:
x=15
b) KeywordArguments:
Keyword arguments are arguments that identify the parameters by their names. For
example, the definition of a function that displays grocery item and its price can be written
as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention which
value is for what. For example,
grocery(item=’sugar’, price=50.75)
Here,wearementioningakeyword„item‟anditsvalueandthenanotherkeyword„price‟and its
value. Please observe these keywords are nothing but the parameter names which receive
these values. We can change the order of the argumentsas:
grocery(price=88.00, item=’oil’)
In this way, even though we change the order of the arguments, there will not be any problem
as the parameter names will guide where to store that value.
def grocery(item,price):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments
Output:
item= sugar
price= 50.75
item= oil price=
88.0
c) DefaultArguments:
We can mention some defaultvalue for the function parameters in the definition.
Let‟s take the definition of grocery( ) function as:
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But the second
argument is „price‟ and its default value is mentioned to be 40.00. at the time of calling this
function, if we do not pass „price‟ value, then the default value of 40.00 is taken. If we
mention the „price‟ value, then that mentioned value is utilized. So, a default argument is an
argument that assumes a default value if a value is not provided in the function call for that
argument.
Example: def grocery(item,price=40.00):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75)
grocery(item="oil")
result=decor1(decor2(num))
print result()
Output:
22
Example-3: A python program to create two decorators to the same function using „@‟
symbol.
def decor1(fun):
def inner():
value=fun()
return value+2
return inner
def decor2(fun):
def inner():
value=fun()
return value*2
return inner
@decor1
@decor2
def num():
return 10
print num()
Output:
22
Modules:
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix.py appended. Within a module, the module‟s name (as a string)
is available as the value of the global variable __name. For instance, use yourfavourite text
editor to create a file called fibo.py in the current directory with the followingcontents:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0,1
while b <n:
printb,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result =[]
a, b = 0,1
while b < n:
result.append(b)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following command:
>>>import fibo
This does not enter the names of the functions defined in fibodirectly in the current symbol
table; it only enters the module name fibothere. Using the module name you can access the
functions:
>>>fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>>fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55,89]
>>>fibo.name
'fibo'
Ex:
student = [556, “Mothi”, 84, 96, 84, 75, 84 ] print
student
print student[0] # Access 0th element
print student[0:2] # Access 0th to 1st elements
print student[2: ] # Access 2nd to end of list elements print
student[ :3] # Access starting to 2nd elements print student[ : ] #
Access starting to ending elements print student[-1] # Access last
index value
print student[-1:-7:-1] # Access elements in reverse order
Output:
[556, “Mothi”, 84, 96, 84, 75, 84]
Mothi
[556, “Mothi”]
[84, 96, 84, 75, 84]
[556, “Mothi”, 84]
[556, “Mothi”, 84, 96, 84, 75, 84]
Output:
12345
When we clone a list like this, a separate copy of all the elements is stored into „y‟.
Thelists„x‟and„y‟areindependentlists.Hence,anymodificationsto„x‟willnotaffect„y‟ and
viceversa.
Methods in Lists:
Method Description
lst.index(x) Returns the first occurrence of x in the list.
lst.append(x) Appends x at the end of the list.
lst.insert(i,x) Inserts x to the list in the position specified by i.
lst.copy() Copies all the list elements into a new list and returns it.
lst.extend(lst2) Appends lst2 to list.
lst.count(x) Returns number of occurrences of x in the list.
lst.remove(x) Removes x from the list.
lst.pop() Removes the ending element from the list.
lst.sort() Sorts the elements of list into ascending order.
lst.reverse() Reverses the sequence of elements in the list.
lst.clear() Deletes all elements from the list.
max(lst) Returns biggest element in the list.
min(lst) Returns smallest element in the list.
Nested Lists:
A list within another list is called a nested list. We know that a list contains several
elements. When we take a list as an element in another list, then that list is called a nested list.
Example:
a=[10,20,30]
b=[45,65,a]
printb # display [ 45, 65, [ 10, 20, 30 ]]
printb[1] # display65
printb[2] # display [ 10, 20, 30 ]
printb[2][0] # display10
print b[2][1] # display 20 print b[2][2]
# display 30 for x in b[2]:
print x, # display 10 2030
mat=[[1,2,3],[4,5,6],[7,8,9]]
for r in mat:
print r
print ""
m=len(mat)
n=len(mat[0])
for i in range(0,m):
for j in range(0,n):
print mat[i][j],
print ""
print ""
One of the main use of nested lists is that they can be used to represent matrices. A
matrix represents a group of elements arranged in several rows and columns. In python,
matrices are created as 2D arrays or using matrix object in numpy. We can also create a
matrix using nested lists.
List Comprehensions:
List comprehensions represent creation of new lists from an iterable object (like a list,
set, tuple, dictionary or range) that satisfy a given condition. List comprehensions contain
very compact code usually a single statement that performs the task.
We want to create a list with squares of integers from 1 to 100. We can write codeas: squares=[ ]
for i in range(1,11):
squares.append(i**2)
The preceding code will create „squares‟ list with the elements as shown below:
[ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The previous code can rewritten in a compact way as:
squares=[x**2 for x inrange(1,11)]
This is called list comprehension. From this, we can understand that a list
comprehension consists of square braces containing an expression (i.e., x**2). After the
expression, a fro loop and then zero or more if statements can be written.
[ expression for item1 in iterable if statement1
for item1 in iterable if statement2
for item1 in iterable if statement3…..]
Example:
Even_squares = [ x**2 for x in range(1,11) ifx%2==0]
It will display the list even squares aslist.
[ 4, 16, 36, 64, 100]
Example-2:
However, you can always delete the entire tuple by using the statement.
Note that this exception is raised because you are trying print the deleted element.
Operations on set:
Sno Operation Result
1 len(s) number of elements in set s (cardinality)
2 x in s test x for membership in s
3 x not in s test x for non-membership in s
s.issubset(t)
4 (or) test whether every element in s is in t
s <= t
s.issuperset(t)
5 (or) test whether every element in t is in s
s >= t
Returns True if two sets are equivalent and returns
6 s = = t
False.
Returns True if two sets are not equivalent and
7 s ! = t
returns False.
s.union(t)
8 (or) new set with elements from both s and t
s|t
s.intersection(t)
9 (or) new set with elements common to s and t
s & t
Note:
To create an empty set you cannot write s={}, because python will make this as a
directory. Therefore, to create an empty set use set( )function.
s=set() s={}
printtype(s) # display<type„set‟> print type(s) # display <type„dict‟>
Updating a set:
Since sets are unordered, indexing has no meaning. Set operations do not allow users
to access or change an element using indexing or slicing.
Bubble Sort:
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that
repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps
them if they are in the wrong order. The pass through the list is repeated until no swaps are
needed, which indicates that the list is sorted.
defbubbleSort(arr):
n =len(arr)
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm
maintains two subarrays in a given array.
Insertion Sort:
Quick sort:
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of
data into smaller arrays. A large array is partitioned into two arrays one of which holds values
smaller than the specified value, say pivot, based on which the partition is made and another
array holds values greater than the pivot value.
Quick sort partitions an array and then calls itself recursively twice to sort the two
resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and
worst case complexity are of Ο(n2), where n is the number of items. The algorithm is given
below:
Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot
def quicksort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
p = partition(alist, start, end)
quicksort(alist, start, p)
quicksort(alist, p + 1, end)
def partition(alist, start, end):
pivot = alist[start]
DATA STRUCTURES USING PYTHON Page 78
i = start + 1
j = end - 1
while True:
while (i<= j and alist[i]<= pivot):
i=i+1
while (i<= j and alist[j]>= pivot):
j=j-1
if i<= j:
alist[i], alist[j] = alist[j], alist[i]
else:
alist[start], alist[j] = alist[j], alist[start]
return j
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
quicksort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)
Linked Lsit:
A linked list is a sequence of data structures, which are connected together via links.Linked
List is a sequence of links which contains items. Each link contains a connection to another
link. Linked list is the second most-used data structure after array. Following are the important
terms to understand the concept of Linked List.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
LinkedList − A Linked List contains the connection link to the first link called First.
As per the above illustration, following are the important points to be considered.
Linked List contains a link element called first.
Each link carries a data field(s) and a link field called next.
Each link is linked with its next link using its next link.
Last link carries a link as null to mark the end of the list.
A linked list is created by using the node class we studied in the last chapter. We create a Node
object and create another class to use this ode object. We pass the appropriate values thorugh
the node object to point the to the next data elements. The below program creates the linked list
with three data elements. In the next section we will see how to traverse the linked list.
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
list1 = SLinkedList()
list1.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
list1.headval.nextval = e2
# Link second Node to third node
e2.nextval = e3
Singly linked lists can be traversed in only forwrad direction starting form the first data element.
We simply print the value of the next data element by assgining the pointer of the next node to
the current data element.
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
Inserting element in the linked list involves reassigning the pointers from the existing nodes to
the newly inserted node. Depending on whether the new data element is getting inserted at the
beginning or at the middle or at the end of the linked list, we have the below scenarios.
This involves pointing the next pointer of the new data node to the current head of the linked
list. So the current head of the linked list becomes the second data element and the new node
becomes the head of the linked list.
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
# Print the linked list
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
def AtBegining(self,newdata):
NewNode = Node(newdata)
# Update the new nodes next val to existing node
NewNode.nextval = self.headval
self.headval = NewNode
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
list.headval.nextval = e2
e2.nextval = e3
This involves pointing the next pointer of the the current last node of the linked list to the new
data node. So the current last node of the linked list becomes the second last data node and the
new node becomes the last node of the linked list.
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
# Function to add newnode
def AtEnd(self, newdata):
NewNode = Node(newdata)
if self.headval is None:
self.headval = NewNode
return
laste = self.headval
while(laste.nextval):
laste = laste.nextval
laste.nextval=NewNode
# Print the linked list
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
list.headval.nextval = e2
e2.nextval = e3
list.AtEnd("Thu")
list.listprint()
This involves chaging the pointer of a specific node to point to the new node. That is possible
by passing in both the new node and the existing node after which the new node will be
inserted. So we define an additional class which will change the next pointer of the new node to
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
# Function to add node
def Inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return
NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode
# Print the linked list
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Thu")
list.headval.nextval = e2
e2.nextval = e3
list.Inbetween(list.headval.nextval,"Fri")
list.listprint()
Removing an Item form a Liked List
We can remove an existing node using the key for that node. In the below program we locate
the previous node of the node which is to be deleted. Then point the next pointer of this node to
the next node of the node to be deleted.
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
def Atbegining(self, data_in):
NewNode = Node(data_in)
NewNode.next = self.head
self.head = NewNode
Stack:
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).
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they
are pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of stack.
isEmpty: Returns true if stack is empty, else false
class Stack:
def __init__(self):
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use list pop method to remove element
def remove(self):
if len(self.stack) <= 0:
return ("No element in the Stack")
else:
return self.stack.pop()
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
DATA STRUCTURES USING PYTHON Page 85
Queue:
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open
at both its ends. One end is always used to insert data (enqueue) and the other is used to remove
data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first
will be accessed first.
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
def size(self):
return len(self.queue)
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size())
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
# Pop method to remove element
def removefromq(self):
if len(self.queue)>0:
return self.queue.pop()
return ("No elements in Queue!")
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
DATA STRUCTURES USING PYTHON Page 86
print(TheQueue.removefromq())
print(TheQueue.removefromq())