CSE 114 Unit 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

Unit 5

UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
What is a Module?
• Consider a module to be the same as a code library.
• A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python
object with arbitrarily named attributes that you can bind and reference.
• Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
• We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.

Modular programming refers to the process of breaking a large, unwieldy


programming task into separate, smaller, more manageable subtasks or modules.
Individual modules can then be cobbled together like building blocks to create a larger
application.
By Ms Preeti Kaushik
There are several advantages to modularizing code in a large application:
• Simplicity: Rather than focusing on the entire problem at hand, a module typically
focuses on one relatively small portion of the problem. If you’re working on a single
module, you’ll have a smaller problem domain to wrap your head around. This makes
development easier and less error-prone.

• Maintainability: Modules are typically designed so that they enforce logical boundaries
between different problem domains. If modules are written in a way that minimizes
interdependency, there is decreased likelihood that modifications to a single module will
have an impact on other parts of the program. (You may even be able to make changes to
a module without having any knowledge of the application outside that module.) This
makes it more viable for a team of many programmers to work collaboratively on a large
application.

• Reusability: Functionality defined in a single module can be easily reused (through an


appropriately defined interface) by other parts of the application. This eliminates the
need to recreate duplicate code.

• Scoping: Modules typically define a separate namespace, which helps avoid collisions
between identifiers in different areas of a program.
By Ms Preeti Kaushik
Importing modules

• Both types of modules can be imported:


a) Built in like platform, math , random etc
b) User defined module

• List of built-in python modules: https://docs.python.org/3/py-modindex.html

By Ms Preeti Kaushik
Create a module
To create a module just save the code you want in a file with the file extension .py:

Example
Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule Output:


mymodule.greeting("Jonathan") Hello Jonathan
By Ms Preeti Kaushik
Variables in module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

Example
Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:

import mymodule

Output:
a = mymodule.person1["age"]
36
print(a)

By Ms Preeti Kaushik
Naming a Module
• You can name the module file whatever you like, but it must have the file extension
.py

Re-naming a Module
• You can create an alias when you import a module, by using the as keyword:

Example
• Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

By Ms Preeti Kaushik
Built-in Modules
There are several built-in modules in Python, which you can import
whenever you like.

Example
Import and use the platform module:

import platform
x = platform.system()
print(x)

Output: Windows

By Ms Preeti Kaushik
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in
a module. The dir() function:

Example
List all the defined names belonging to the platform module:

import platform
x = dir(platform)
print(x)

By Ms Preeti Kaushik
Import From Module
You can choose to import only parts from a module, by using the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:

from mymodule import person1


print (person1["age"])
By Ms Preeti Kaushik
Unit 5
UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
• Python math module functions are categorized into following
category:
a) Arithmetic functions
b) Power functions
c) Logarithmic functions etc
d) Constants (Pi , Tau , Euler’s number, Infinity, Not a number (NaN))

By Ms Preeti Kaushik
Study link for maths function
• https://www.w3schools.com/python/module_math.asp

• https://www.programiz.com/python-programming/modules/math

• https://realpython.com/python-math-module/

By Ms Preeti Kaushik
Example:

import math

#Return factorial of a number


print(math.factorial(9))
Output:
print(math.floor(1.4))
print(math.floor(-5.3))
print (math.gcd(26, 12)) 362880
print (math.gcd(12, 6)) 1
# Convert angles from radians to degrees: -6
print (math.degrees(8.90))
print (math.degrees(-20)) 2
print (math.degrees(1))
6
# Add items in a tuple
a = (1, 2, 3, 4, 5)
509.9324376664327
-1145.9155902616465
# Print the sum of all items
print(math.fsum(a)) 57.29577951308232
15.0
#Return the value of 9 raised to the power of 3 729.0
print(math.pow(9, 3)) 0.0
-0.9424888019316975
# Return the sine of different values -0.5440211108893698
print (math.sin(0.00))
print (math.sin(-1.23)) 2
print (math.sin(10)) -99

# Return the truncated integer parts of different numbers


print(math.trunc(2.77))
print(math.trunc(-99.29))
By Ms Preeti Kaushik
Unit 5
UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
Study link for random module function
• https://www.w3schools.com/python/module_random.asp

By Ms Preeti Kaushik
Unit 5
UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
• Matplotlib is a comprehensive library for creating static, animated, and
interactive visualizations in Python.

• Matplotlib is an amazing visualization library in Python for 2D plots of arrays.


Matplotlib is a multi-platform data visualization library built on NumPy arrays
and designed to work with the broader SciPy stack. It was introduced by John
Hunter in the year 2002.
• One of the greatest benefits of visualization is that it allows us visual access to
huge amounts of data in easily digestible visuals. Matplotlib consists of several
plots like line, bar, scatter, histogram etc.
• Matplotlib comes with a wide variety of plots. Plots helps to understand trends,
patterns, and to make correlations. They’re typically instruments for reasoning
about quantitative information.
By Ms Preeti Kaushik
Example 1 : Line plot
Example 2: Line plot
# importing matplotlib module
from matplotlib import pyplot as plt
from matplotlib import pyplot as plt
#Plotting to our canvas
x = [5, 2, 9, 4, 7] # x-axis values plt.plot([1,2,3],[4,5,1])
y = [10, 5, 8, 4, 2] # Y-axis values
#Showing what we plotted
plt.plot(x,y) # Function to plot plt.show()
plt.show() # function to show the plot

By Ms Preeti Kaushik
Add title, label to plot
from matplotlib import pyplot as plt

x = [5,2,7]
y = [2,16,4]
plt.plot(x,y)
plt.title('Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

By Ms Preeti Kaushik
Styling techniques, width or color of a particular line, grid lines
• First, you need to import the style package from python matplotlib library and then use styling functions as shown
in below code:

from matplotlib import pyplot as plt


from matplotlib import style

style.use('ggplot')
x = [5,8,10]
y = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.plot(x,y,'g',label='line one', linewidth=5)
plt.plot(x2,y2,'c',label='line two',linewidth=5)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.legend()
plt.grid(True,color='k')
plt.show()
By Ms Preeti Kaushik
Example : Bar plot
A bar graph uses bars to compare data among different categories. It is well suited when you want to measure the
changes over a period of time. It can be represented horizontally or vertically. Also, the important thing to keep in
mind is that longer the bar, greater is the value.
Example 2:
from matplotlib import pyplot as plt
Example 1:
from matplotlib import pyplot as plt plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",width=.5)
x = [5, 2, 9, 4, 7] # x-axis values plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
y = [10, 5, 8, 4, 2] # Y-axis values label="Audi", color=‘y',width=.5)
plt.legend()
plt.bar(x,y) # Function to plot the bar plt.xlabel('Days')
plt.show() # function to show the plot plt.ylabel('Distance (kms)')
plt.title('Information')
plt.show()

By Ms Preeti Kaushik
Example: Histogram
Histograms are used to show a distribution whereas a bar chart is used to compare different entities. Histograms are
useful when you have arrays or a very long list. Let’s consider an example where I have to plot the age of population
with respect to bin. Now, bin refers to the range of values that are divided into series of intervals. Bins are usually
created of the same size.
In the below code, we have created the bins in the interval of 10 which means
the first bin contains elements from 0 to 9, then 10 to 19 and so on.
Example 1:
from matplotlib import pyplot as plt Example 2:
import matplotlib.pyplot as plt
y = [10, 5, 8, 4, 2] # Y-axis values population_age =
plt.hist(y) # Function to plot histogram [22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,115,80,75,6
5,54,44,43,42,48]
plt.show() # Function to show the plot bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_age, bins, histtype='bar', rwidth=0.8)
plt.xlabel('age groups')
plt.ylabel('Number of people')
plt.title('Histogram')
plt.show()

By Ms Preeti Kaushik
Example: scatter plot
Usually we need scatter plots in order to compare variables, for example, how much one variable is affected by another
variable to build a relation out of it. The data is displayed as a collection of points, each having the value of one variable
which determines the position on the horizontal axis and the value of other variable determines the position on the
vertical axis.
Example 1: Example 2:
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
x = [1,1.5,2,2.5,3,3.5,3.6]
x = [5, 2, 9, 4, 7] # x-axis values y = [7.5,8,8.5,9,9.5,10,10.5]
y = [10, 5, 8, 4, 2] # Y-axis values
x1=[8,8.5,9,9.5,10,10.5,11]
plt.scatter(x, y) # Function to plot scatter y1=[3,3.5,3.7,4,4.5,5,5.2]
plt.show() # function to show the plot
plt.scatter(x,y, label='high income low saving',color='r')
plt.scatter(x1,y1,label='low income high savings',color='b')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
plt.legend()
plt.show()

By Ms Preeti Kaushik
Example: Area plot
• Area plots are pretty much similar to the line plot. They are also known as stack plots. These plots can be used to track changes over time
for two or more related groups that make up one whole category. For example, let’s compile the work done during a day into categories,
say sleeping, eating, working and playing. Consider the below code:

Example:
import matplotlib.pyplot as plt
days = [1,2,3,4,5]

sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]

plt.plot([],[],color='m', label='Sleeping', linewidth=5)


plt.plot([],[],color='c', label='Eating', linewidth=5)
plt.plot([],[],color='r', label='Working', linewidth=5)
plt.plot([],[],color='k', label='Playing', linewidth=5)

plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('Stack Plot')
plt.legend()
plt.show() By Ms Preeti Kaushik
Example: pie chart
• A pie chart refers to a circular graph which is broken down into segments i.e. slices of pie. It is basically used to show the percentage or proportional data where each
slice of pie represents a category. In the above pie chart, we have divided the circle into 4 sectors or slices which represents the respective category (playing, sleeping,
eating and working) along with the percentage they hold. Now, if you have noticed these slices adds up to 24 hrs, but the calculation of pie slices is done automatically
for you. In this way, pie charts are really useful as you don’t have to be the one who calculates the percentage or the slice of the pie.

Example:
import matplotlib.pyplot as plt

days = [1,2,3,4,5]

sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']

plt.pie(slices,
labels=activities,
colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')

plt.title('Pie Plot')
plt.show()

By Ms Preeti Kaushik
Saving your plot
Example:
import matplotlib.pyplot as plt

plt.grid(True, linewidth=0.5, color='#ff0000', linestyle='-')

#Plot a line graph


plt.plot([10, 20, 30, 40, 50])
# Add labels and title
plt.title("Interactive Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

plt.savefig("foo.png", bbox_inches='tight')
By Ms Preeti Kaushik
Drawing multiple plots
• Now, let us see how to handle multiple plots. For this, I have to import numpy module

Example:
import numpy as np
import matplotlib.pyplot as plt

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2))
plt.subplot(222)
plt.plot(t2, np.cos(2*np.pi*t2))
plt.show()

By Ms Preeti Kaushik
python matplotlib has some disadvantages. Some of them are listed
below:
• They are heavily reliant on other packages, such as NumPy.
• It only works for python, so it is hard or impossible to be used in
languages other than python. (But it can be used from Julia via PyPlot
package).

By Ms Preeti Kaushik
Unit 5
UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
• Packages are a way of structuring many packages and modules which helps in a
well-organized hierarchy of data set, making the directories and modules easy to
access.
• A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and subpackages and sub-
subpackages, and so on.
• As our application program grows larger in size with a lot of modules, we place
similar modules in one package and different modules in different packages. This
makes a project (program) easy to manage and conceptually clear.
• Similarly, as a directory can contain subdirectories and files, a Python package can
have sub-packages and modules.
• Just like there are different drives and folders in an OS to help us store files,
similarly packages help us in storing other sub-packages and modules, so that it
can be used by the user when necessary.

By Ms Preeti Kaushik
• A directory must contain a file named __init__.py in order for Python to
consider it as a package. This file can be left empty but we generally place
the initialization code for that package in this file.

• Packages are a way of structuring Python’s module namespace by using


"dotted module names". A.B stands for a submodule named B in a package
named A.

• a module can contain multiple objects, such as classes, functions, etc. A


package can contain one or more relevant modules. Physically, a package is
actually a folder containing one or more module files.

By Ms Preeti Kaushik
By Ms Preeti Kaushik
creating and installing a package
Let's create a package named mypackage, using the following
steps:
• Create a new folder named D:\MyApp.
• Inside MyApp, create a subfolder with the name 'mypackage'.
• Create an empty __init__.py file in the mypackage folder.
• Using a Python editor , create modules greet.py and
functions.py with following code:

greet.py
def SayHello(name):
print("Hello " + name)
return

functions.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y

By Ms Preeti Kaushik
Importing a Module from a Package
• Now, to test our package, invoke the Python prompt from the MyApp folder.
D:\MyApp>python

• Import the functions module from the mypackage package and call its power() function.
>>> from mypackage import functions
>>> functions.power(3,2)
9

• It is also possible to import specific functions from a module in the package


>>> from mypackage.functions import sum
>>> sum(10,20)
30
>>> average(10,12)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
NameError: name 'average' is not defined

By Ms Preeti Kaushik
__init__.py
The package folder contains a special file called __init__.py, which stores the package's content. It serves two purposes:

a) The Python interpreter recognizes a folder as the package if it contains __init__.py file.
b) __init__.py exposes specified resources from its modules to be imported.

An empty __init__.py file makes all functions from above modules available when this package is imported. Note that __init__.py
is essential for the folder to be recognized by Python as a package. You can optionally define functions from individual modules to
be made available.

The __init__.py file is normally kept empty. However, it can also be used to choose specific functions from modules in the package
folder and make them available for import. Modify __init__.py as below:

Program
__init__.py
from .functions import average, power
from .greet import SayHello

The specified functions can now be imported in the interpreter session or another executable script.
By Ms Preeti Kaushik
Create test.py in the MyApp folder to test mypackage.

Program:test.py
from mypackage import power, average, SayHello
SayHello(world)
x=power(3,2)
print("power(3,2) : ", x)

Note that functions power() and SayHello() are imported from the package and not from their
respective modules, as done earlier. The output of above script is:

D:\MyApp>python test.py
Hello world
power(3,2) : 9

Link to read: https://www.tutorialsteacher.com/python/python-package

By Ms Preeti Kaushik
Unit 5
UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
Linear /sequential search
• Linear search is a very simple search algorithm. In this type of search, a
sequential search is made over all items one by one. Every item is checked
and if a match is found then that particular item is returned, otherwise the
search continues till the end of the data collection.

• A simple approach is to do linear search, i.e


a) Start from the leftmost element of list and one by one compare x with each
element of the list.
b) If x matches with an element, return True.
c) If x doesn’t match with any of elements, return False.

By Ms Preeti Kaushik
Algorithm: Pseudocode:
Linear_Search ( LIST A, Value x) procedure linear_search (list, value)
Step 1: Set i to 1
Step 2: if i > n then go to step 7 for each item in the list
Step 3: if A[i] = x then go to step 6 if match item == value
Step 4: Set i to i + 1 return the item's location
Step 5: Go to Step 2 end if
Step 6: Print Element x Found at index i end for
and go to step 8
Step 7: Print element not found end procedure
Step 8: Exit

By Ms Preeti Kaushik
• Best complexity O(1)
• Worst complexity O(n)

Algorithm
pseudocode
Program
Explain the method-al,pro

By Ms Preeti Kaushik
Example #1: Linear Search on Lists
def search(list,n): Output 1:
for i in range(len(list)): enter to search abc
if list[i] == n: Found
return True
return False Output 2:
enter to search67
# list which contains both string and numbers. Not Found
list = [1, 2, 'abc', 4,'xyz', 6]

n = input("enter to search")
if search(list, n):
print("Found")
else:
print("Not Found")
By Ms Preeti Kaushik
Example #2: Linear Search on tuple
# Search function with parameter list name Output 1:
# and the value to be searched enter to search abc
def search(list,n): Found

for i in range(len(list)): Output 2:


if list[i] == n: enter to search67
return True Not Found
return False

# list which contains both string and numbers.


list = (1, 2, 'abc', 4,'xyz', 6)

# Driver Code
n = input("enter to search")

if search(list, n):
print("Found")
else:
print("Not Found")

By Ms Preeti Kaushik
Unit 5
UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
• Binary Search: Search a sorted array by repeatedly dividing the search
interval in half. Begin with an interval covering the whole array. If the
value of the search key is less than the item in the middle of the interval,
narrow the interval to the lower half. Otherwise narrow it to the upper
half. Repeatedly check until the value is found or the interval is empty.

We basically ignore half of the elements just after one comparison.


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

By Ms Preeti Kaushik
• Binary search algorithm requires already sorted collection.
• Binary search, (also known as half-interval search, logarithmic search,
or binary chop) is a search algorithm that finds the position of a target
value within a sorted array.
• Binary search compares the target value to the middle element of the
array. If they are unequal, the half in which the target cannot lie is
eliminated and the search continues on the remaining half until it is
successful or the remaining half is empty.
• Once the target element found or collection is empty, then the search is
over.

By Ms Preeti Kaushik
• Binary Search basically reduces the search space to half at each step.
By search space we mean sub-array of given array where the target
value is located (if present in the array). Initially, the search space is
the entire array and binary search redefine the search space at every
step of the algorithm by using the property of the array that it is
sorted. It does so by comparing the mid value in the search space to
the target value. If the target value matches the middle element, its
position in the array is returned else it discards half of the search
space based on the comparison result.

By Ms Preeti Kaushik
23 45 12 16 56 78 34 search 12

By Ms Preeti Kaushik
By Ms Preeti Kaushik
def binarysearch(arr,l,r,x):
Please Enter the Total Number of Elements : 7
while l<=r:
mid=l+(r-l)//2; Please enter the 0 Element of List1 : 23

Please enter the 1 Element of List1 : 45


if arr[mid]==x: # Check if x is present at mid
return mid Please enter the 2 Element of List1 : 12

Please enter the 3 Element of List1 : 16


elif arr[mid]<x: # If x is greater, ignore left half
l=mid + 1 Please enter the 4 Element of List1 : 56

Please enter the 5 Element of List1 : 78


else: # If x is smaller, ignore right half
r = mid - 1 Please enter the 6 Element of List1 : 34
elements entered are: [23, 45, 12, 16, 56, 78, 34]
# If we reach here, then the element was not present sorted elements are: [12, 16, 23, 34, 45, 56, 78]
return -1
enter number to search12
Element is present at index 0

arr = [] Output:
number = int(input("Please Enter the Total Number of Elements : "))
Please Enter the Total Number of Elements : 7

for i in range(number): Please enter the 0 Element of List1 : 23


value = int(input("Please enter the %d Element of List1 : " %i))
Please enter the 1 Element of List1 : 45
arr.append(value)
Please enter the 2 Element of List1 : 12
print(" elements entered are:", arr)
Please enter the 3 Element of List1 : 16

arr.sort() Please enter the 4 Element of List1 : 56


Iteratively program
print(" sorted elements are:", arr)
Please enter the 5 Element of List1 : 78
solution
x = int(input("enter number to search")) Please enter the 6 Element of List1 : 34
elements entered are: [23, 45, 12, 16, 56, 78, 34]
sorted elements are: [12, 16, 23, 34, 45, 56, 78]
result=binarySearch(arr,0,len(arr)-1,x)
enter number to search98
Element is not present in list
if result != -1:
print ("Element is present at index % d" % result)
else:
print ("Element is not present in list")
By Ms Preeti Kaushik
Unit 5
UNIT 5 A: Modules: Importing module, Math module, Random module

UNIT 5 B: Matplotlib, Packages

UNIT 5 C: Applications: Searching Linear Search, Binary Search. Sorting: Bubble Sort

By Ms Preeti Kaushik
• Bubble sort is a very basic and simple sorting algorithm which sort an unsorted
array.
• It works by comparing each pair of adjacent element and swap them if they are in a
wrong order.
• The average and worst-case time complexity of bubble sort is – O(n2)
• Bubble sort is not efficient for large data set.

The steps of performing a bubble sort are:


• Compare the first and the second element of the list and swap them if they are in
wrong order.
• Compare the second and the third element of the list and swap them if they are in
wrong order.
• Proceed till the last element of the list in a similar fashion.
• Repeat all of the above steps until the list is sorted.

By Ms Preeti Kaushik
By Ms Preeti Kaushik
By Ms Preeti Kaushik
By Ms Preeti Kaushik
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp

alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)

Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]

By Ms Preeti Kaushik
Example 3:
# Python program for Bubble Sort
def bubblesort(a, number):
for i in range(number -1):
for j in range(number - i - 1):
if(a[j] > a[j + 1]):
temp = a[j] Output:
a[j] = a[j + 1] Please Enter the Total Number of Elements
a[j + 1] = temp :4
Please enter the 0 Element of List1 : 23
a = [] Please enter the 1 Element of List1 : 56
number = int(input("Please Enter the Total Number of Elements : ")) Please enter the 2 Element of List1 : 2
for i in range(number): Please enter the 3 Element of List1 : 27
value = int(input("Please enter the %d Element of List1 : " %i)) The Sorted List in Ascending Order : [2, 23,
a.append(value) 27, 56]

bubblesort(a, number)
print("The Sorted List in Ascending Order : ", a)

By Ms Preeti Kaushik
Reading link for numpy
• https://www.edureka.co/blog/python-numpy-tutorial/

By Ms Preeti Kaushik

You might also like