SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
MODULE V: LINEAR SEARCH
Q.1 what are Lists
A list in Python is an ordered group of items or elements. It's important to notice
that these list elements don't have to be of the same type. It can be an arbitrary
mixture of elements like numbers, strings, and other lists and so on. A list is
created by placing all the items (elements) inside a square bracket [ ], separated
by commas.
The main properties of Python lists:
• They are ordered
• The contain arbitrary objects
• Elements of a list can be accessed by an index
• They are arbitrarily nestable, i.e. they can contain other lists as sub-lists
• Variable size
• They are mutable, i.e. the elements of a list can be changed
List Description
[ ] An empty list
[1,1,2,3,5,8] A list of integers
[42, "What's the question?", 3.1415] A list of mixed data types
[ "Riyas", "Priya", "Zubair", "Manazir", " Ibrahim" ] A list of Strings
[ ["Chennai","Tamilnadu", 600048],
["Hyderabad","Telangana",5000321 ] ]
A nested list
Q1.1 What are the various List Methods available in Python?
Methods that are available with list object in Python programming are tabulated
below. They are accessed as list.Method (). Some of the methods are as follows:
Python List Methods
insert() - Insert an item at the defined index
index() - Returns the index of the first matched item
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
remove() - Removes an item from the list
clear() - Removes all items from the list
copy() - Returns a shallow copy of the list
reverse() - Reverse the order of items in the list
sort() - Sort items in a list in ascending order
count() - Returns the count of number of items passed as an argument
pop() - Removes and returns an element at the given index
Q.2 How to do List Assignment.
A list refers to a collection of objects; it represents an ordered sequence of data.
In that sense, a list is similar to a string, except a string can hold only characters.
We may access the elements contained in a list via their position within the list. A
list need not be homogeneous; that is, the elements of a list do not all have to be
of the same type.
Like any other variable, a list variable can be local or global, and it must be
defined (assigned) before it is used.
The following code fragment declares a list named list that holds the integer
values 2,−3,0,4,−1:
List = [2, -3, 0, 4, -1]
The right-hand side of the assignment statement is a literal list. The elements of
the list appear within square brackets [ ], the elements are separated by commas.
The following statement:
a = [] # assigns the empty list to a.
We can print list literals and lists referenced through variables:
List = [2, -3, 0, 4, -1] # Assign the list
print ([2, -3, 0,4,-1]) # Print a literal list
print (List) # Print a List variable
List = [2, -3, 0, 4, -1] # Assign the list
List [0] = 5 # Make the first element 5
print(List [1]) # Print the second element -3
List [4] = 12 # Make the last element 12
print (List) # Print a list variable
print( [10, 20, 30] [1] ) # Print 2nd
element of list
Q.3 List Bounds.
In the following code fragment: a = [10, 20, 30, 40]
All of the following expressions are valid: a[0], a[1], a[2] and a[3]. The expression
a[4] does not represent a valid element in the list.
print (a[4]) # Out-of-bounds access
An attempt to use above expression, as in a = [10, 20, 30, 40] results in a run-
time exception. The interpreter will insist that the programmer use an integral
value for an index, but in order to prevent a run-time exception the programmer
must ensure that the index used is within the bounds of the list.
A negative list index represents a negative offset from an imaginary element one
past the end of the list. For list lst, the expression
element in lst and The expression
so forth.
Q. 4 Slicing.
We can make a new list from a portion of an existing list using a technique known
as slicing. A list slice is an expression of the form
where
• list is a list of variable referring to a list object, a literal list, or some other
expression that evaluates to a list.
• begin is an integer representing the starting index of
the list.
• end is an integer that is one larger than the index of the last element in a
subsequence of the list.
We can access a range of items in a list by using the
Slicing can be best visualized by con
elements as shown below. So if we want to access a range, we need two indices
that will slice that portion from the list
My_List = ['p',
print(My_list [ 2:5 ] )
print(My_list [: -5] )
print(My_list[5:])
print(My_list[:])
A negative list index represents a negative offset from an imaginary element one
For list lst, the expression lst[-1] represents the
The expression lst[-2] represents the next to last element
We can make a new list from a portion of an existing list using a technique known
an expression of the form list [begin: end].
is a list of variable referring to a list object, a literal list, or some other
expression that evaluates to a list.
is an integer representing the starting index of a subsequence of
is an integer that is one larger than the index of the last element in a
subsequence of the list.
We can access a range of items in a list by using the slicing operator
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 two indices
that portion from the list
List = ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z' ]
Output : ['O', 'G', 'R']
Output : ['P', 'R', 'O', 'G']
Output : ['A', 'M', 'I', 'Z']
Output : ['P', 'R', 'O', 'G', 'R', 'A', 'M', 'I', 'Z']
A negative list index represents a negative offset from an imaginary element one
represents the last
next to last element, and
We can make a new list from a portion of an existing list using a technique known
is a list of variable referring to a list object, a literal list, or some other
a subsequence of
is an integer that is one larger than the index of the last element in a
slicing operator (colon).
sidering the index to be between the
elements as shown below. So if we want to access a range, we need two indices
['P', 'R', 'O', 'G', 'R', 'A', 'M', 'I', 'Z']
Q.5 List and Functions.
A list can be passed to a function, since list objects are mutable; passing to a
function a reference to a list object binds the formal parameter to the list object.
This means the formal parameter becomes an alias of the actual parameter. The
change_list method does attempt to modify list parameter. This means the clear
function will modify the list object outside function.
Eg.1 Passing Immutable Object (List)
def change_list(list1):
list1.append(5);
list1.append(6);
print("list inside function = ",list1)
#defining the list
list1 = [1, 2, 3, 4]
change_list (list1); # function call
print ("list outside function = ", list1);
Output:
list inside function = [1,2,3,4,5,6]
list outside function = [1,2,3,4,5,6]
Q. 6 Prime Generation with List.
fasterprimes.py uses an algorithm developed by the Greek mathematician
Eratosthenes who lived from 274 B.C. to 195 B.C. Called the Sieve of
Eratosthenes, the principle behind the algorithm is simple:
• Make a list of all the integers two and larger.
• Two is a prime number, but any multiple of two cannot be a prime number
(since a multiple of two has two as a factor).
• Go through the rest of the list and mark out all multiples of two (4, 6, 8 ...).
• Move to the next number in the list (in this case, three). If it is not marked
out, it must be prime, so go through the rest of the list and mark out all
multiples of that number (6, 9, 12,..........).
• Continue this process until you have listed all the primes you want.
Fast prime fasterprimes.py implements the Sieve of Eratosthenes
def primes(n):
if n==2: return [2]
elif n<2: return []
s=range(3,n+1,2)
mroot = n ** 0.5
half=(n+1)/2-1
i=0
m=3
while m <= mroot:
if s[i]:
j=(m*m-3)/2
s[j]=0
while j<half:
s[j]=0
j+=m
i=i+1
m=2*i+3
return [2]+[x for x in s if x]
print primes(13)
Output : [2, 3, 5, 7, 11, 13]
print primes(100)
Output : 2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97
Q.7 what is sorting?
Arranging the elements within a list into a particular order is a common activity.
For example, a list of integers may be arranged in ascending order (that is, from
smallest to largest). Many sorting algorithms exist, and some perform much
better than others. We will consider one sorting algorithm that is relatively easy
to implement. The selection sort algorithm is relatively easy to implement and
easy to understand how it works.
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 sub-arrays in a given array.
1) The sub-array which is already sorted.
2) Remaining sub-array which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending
order) from the unsorted sub-array is picked and moved to the sorted sub-array.
import sys
A = [64, 25, 12, 22, 11]
for i in range(0, len(A)): # Traverse through all array elements
for j in range (i+1, len(A)):
if A[i] > A[j]: # comparing 1st
element with 2nd, 3rd
n so on
Temp = A[i] # Swap the minimum element with the first element
A[i] = A[j]
A[j] = Temp
print ("Sorted array n ")
for i in range(0, len(A)):
print("%d" %A[i])
Q What is Flexible sorting.
Consider a situation where we want the behaviour of the sorting function in so
that it arranges the elements in descending order instead of ascending order.
This situation can be easily achieved by simply changing the line
if list[j] < list[small]: # for Ascending order
to be
if list[j] > list[small]: # for Descending order
But consider a situation where we want to change the sort so that it sorts the
elements in ascending order or descending order without changing the if
condition again and again. Therefore, in order to make our function more flexible
we will pass an ordering function as a parameter of functions as parameters to
other functions and arranges the elements in a list two different ways using the
same selection_sort function.
def less_than(m, n):
return m < n
def greater_than(m, n):
return m > n
def selection_sort(list, comp):
n = len(list)
for i in range(n - 1):
small = i
for j in range(i + 1, n):
if comp ( list[j], list[small] ):
small = j
if i != small:
list[i],list[small] = list[small], list[i]
Original_List = [5,1,9,22,6,33,7]
working = Original_List[:]
selection_sort (working, less_than)
print('Ascending: ', working)
selection_sort (working, greater_than)
print('Descending:', working)
Output:
Ascending: [1, 5, 6, 7, 9, 22, 33]
Descending: [33, 22, 9, 7, 6, 5, 1]
Q. 8 Searching Basics:
Searching is a very basic necessity when you store data in different data
structures. Searching a list for a particular element is a common activity.The
simplest approach is to go across every element in the data structure and match it
with the value you are searching for. This is known as linear search. It is inefficient
and rarely used, but creating a program for it gives an idea about how we can
implement some advanced search algorithms
We examine two basic strategies: linear search and binary search.
In Linear search is a sequential search is made over all items one by one for
finding a particular value among list of items. It starts searching the value from
the beginning of the list and continues till the end of the list until the value is
found.
def linear_search (values, search_elm):
search_at = 0 # search_at will give position or index of item
res = False # res will signal whether search is successful or not
while search_at < len(values) and res is False:
if values[search_at] == search_elm: # search_elm is item to search
res = True
else:
search_at = search_at + 1 # increment index
return res
list = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(list, 12))
print(linear_search(list, 91))
Output:
True
False
Binary search is an algorithm for locating the position of an item in a sorted
array. Linear search is acceptable for relatively small lists, but the process of
examining each element in a large list is time consuming.
An alternative to linear search is binary search. In order to perform binary search,
a list must be in sorted order. Binary search exploits the sorted structure of the
list using a clever but simple strategy that quickly zeros in on the element to find:
• If the list is empty, return none.
• Compare x with the middle element, If x matches with middle element,
we return the mid index.
• If the middle element is larger than the element you are seeking, perform
a binary search on the left first half of the list.
• If the middle element is smaller than the element you are seeking,
perform a binary search on the right half of the list.
def binary_search (List, L, U, elm):
if U >= L: # Check U as Upper Bound
mid = int (L + (U - L)/2) # convert into integer
if List[mid] == elm: # If element is at mid
return mid
elif List [mid] > x: # If elm is smaller
return binary_search(List, L, mid-1, elm)
else:
return binary_search(List, mid+1, U, elm)
else:
return -1 # Element not present in List
List = [ 2, 3, 4, 10, 40 , 70, 100]
x = int ( input(“Enter search element:”))
result = binary_search (list, 0, len(list)-1, x)
if result != -1:
print ("Element present at index" result )
else:
print ("Element is not present in list")
Output: Enter search element: 10
Element present at index 3
Q. 9 List Permutation
Sometimes it is useful to consider all the possible arrangements of the elements
within a list. Permutation is an arrangement of objects in a specific order. Order
of arrangement of object is very important. The number of permutations on a set
of n elements is given by n! . For example, there are 2! = 2*1 = 2 permutations of
{1, 2}, namely {1, 2} and {2, 1}.
To test a permutation function, a programmer could check to see to see if it
produces the correct result for all arrangements of a relatively small list. Below
program generates all the permutations of a given list.
def permutation(list):
if len(list) == 0: # If list is empty then there are no permutations
return []
if len(list) == 1: # If one element in list then, only one permutation
return [list]
Cur_list = [] # empty list that will store permutation
for i in range(len(list)): # Iterate the input(list) and calculate the permutation
first_elm = list[i]
remlist = list[: i] + list[i+1:] # Extract remaining list from the list
for p in permutation(remlist):
Cur_list.append ([first_elm] + p)
return Cur_list
data =[1,2,3] # Program will start here
for p in permutation(data):
print (p)
Another Method of Generating Permutations using standard functions.
Q.9.1 Random Permutation
We can generate all the permutations of a list in an orderly fashion. Often,
however, we need to produce one those permutations chosen at random. For
example, we may need to randomly rearrange the contents of an ordered list so
that we can test a sort function to see if it will produce the original list. We could
generate all the permutations, put each one in a list, and select a permutation at
random from that list. This approach is inefficient, especially as the length of the
list to permute grows larger. Fortunately, we can randomly permute the contents
of a list easily and quickly.
from random import randrange
def permute(lst): #Randomly permutes the contents of list lst
n = len(lst)
for i in range(n - 1):
pos = randrange(i, n) # i <= pos < n
lst[i], lst[pos] = lst[pos], lst[i]
a = [1, 2, 3, 4, 5, 6, 7, 8]
print('Before:', a)
permute(a)
print('After :', a)
import itertools
List = [1, 2, 3] # 3! Or 6 permutation can be formed
permutations_object = itertools.permutations(List) # Find permutations of List
permutations_List = List(permutations_object) # Create list from permutations
print(permutations_List)
Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
Output: Before: [1, 2, 3, 4, 5, 6, 7, 8]
After : [4, 6, 1, 7, 8, 3, 5, 2]
After : [3, 5, 1, 6, 8, 7, 2, 4]
Q.10 What are Objects.
Python is an object oriented programming language and almost everything in
Python is an object, with its properties and methods. A Class is like an object
blueprint for creating objects. Classes provide a means of bundling data and
functionality together.
E.g. The assignment statement x = 2
Binds the variable x to an integer object with the value of 2. The name of the class
of object x is int.
An object is an instance of a class which fuse data and functions together. A
typical object consists of two parts: data and methods. An object’s data is
sometimes called its attributes or fields. Methods are like functions, and they also
are known as operations. The data and methods of an object constitute its
members. Using the same terminology as functions, the code that uses an object
is called the object’s client. Just as a function provides a service to its client, an
object provides a service to its client. The services provided by an object can be
more elaborate that those provided by simple functions, because objects make it
easy to store persistent data.
In python a class is created by the keyword class. E.g. Create a class named
My_Class, with a property named x:
class My_Class: # Creating Class
x = 5
obj1 = My_Class() # Creating an Object
print(obj1.x)
Output: 5
class Person:
def __init__ (self, name, age):
self.name = name
self.age = age
per1 = Person("Durga", 21)
print(per1.name, per1.age)
Output: Durga 21
class My_Class:
a = 10
def fun(self) :
print('Hello')
ob1 = My_Class()
# create a new My_Class object ob1
ob.fun() # calling fun with no parameter
Output : Hello
class Person:
def__init__(myobj, name, age):
myobj.name = name
myobj.age = age
def myfunc (p):
print("my name is " + p.name)
per1 = Person("Durga", 21)
per1.myfunc()
Output : My name is Durga
The __init__() function is called automatically every time the class is being used to
create a new object.
The self parameter is a reference to the current instance (per1) of the class, and
is used to access variables that belong to the class. It does not have to be named
self, you can call it whatever you like, but it has to be the first parameter of any
function in the class:
Q. String objects
Strings are like lists is some ways because they contain an ordered sequence of
elements. Strings are distinguished from lists in three key ways:
• Strings must contain only characters, while lists may contain objects of any
type.
• Strings are immutable. The contents of a string object may not be changed.
Lists are mutable objects.
• If two strings are equal with == comparison, they automatically are aliases
(equal with the is operator). This means two identical string literals that
appear in the Python source code refer to the same string object.
E.g. word1 = 'Wow'
word2 = 'Wow'
print('Equality:', word1 == word2, ' Alias:', word1 is word2)
Output : Equality: True Alias: True
We assign word1 and word2 to two distinct string literals. Since the two string
literals contain exactly the same characters, the interpreter creates only one
string object. The two variables word1 and word2 are bound to the same object.
We say the interpreter merges the two strings. Since in some programs strings
may be long, string merging can save space in the computer’s memory.
Strings Methods
Upper : Returns a copy of the original string with all the characters converted to uppercase
Lower: Returns a copy of the original string with all the characters converted to lower case
Center: Returns a copy of the string centred within a string of a given width and optional fill
characters; fill characters default to spaces
Count : Determines the number times the string parameter is found as a substring; the count
includes only non-overlapping occurrences
Find : Returns the lowest index where the string parameter is found as a substring; returns −1
if the parameter is not a substring
E.g
name = input("Please enter your name: ")
print("Hello " + name.upper() + ", how are you?")
Output: Please enter your name: Zamir Hello ZAMIR, how are you?
The expression name. upper() within the print statement represents a method
call. The general form of a method call is
object.methodname (parameterlist)
• object is an expression that represents object and name is a reference to
a string object.
• The period, pronounced dot, associates an object expression with the
method to be called.
• methodname is the name of the method to execute.
• The parameterlist is comma-separated list of parameters to the method.
For some methods the parameter list may be empty, but the parentheses
always are required
Q. List objects
• A list is a data-structure, or it can be considered a container that can be
used to store multiple data at once.
• The list will be ordered and there will be a definite count of it.
• The elements are indexed according to a sequence and the indexing is done
with 0 as the first index.
• Each element will have a distinct place in the sequence and if the same
value occurs multiple times in the sequence, each will be considered
separate and distinct element.
We assigned lists, passed lists to functions, returned lists from functions, and
interacted with the elements of lists.
Since lists are mutable data structures, the list class has both
__getitem__ and __setitem__ methods.
The statement
x = lst[2]
behind the scenes becomes the method call
x = list.__getitem__(lst, 2)
and the statement lst[2] = x maps to list.__setitem__(lst, 2, x)
The code
lst = ["one", "two", "three"]
lst += ["four"] is same as lst.append("four")
print(lst)
Output : ['one', 'two', 'three', 'four']
Few methods available to List objects are...
Count: Returns the number of times an element appears in the list. Does not
modify the list.
Insert: Inserts a new element before the element at a given index. Increases the
length of the list by one and also Modifies the list.
Append: Adds a new element to the end of the list. Modifies the list.
Remove: Removes the first occurrence (lowest index) of a given element from the
list. Index Produces an error if the element is not found. Modifies the list if the
item to remove is in the list.
Reverse: Physically reverses the elements in the list. The list is modified.
Sort: Sorts the elements of the list in ascending order. The list is modified
Index: Returns the lowest index of a given element within the list. Produces an
error if the element does not appear in the list. Does not modify the list.
Q. 11 Geometric,
To introduce simple objects, consider two-dimensional geometric points from
mathematics. We consider a single point object to consist of two real number
coordinates: x and y. We ordinarily represent a point by an ordered pair (x,y). In a
program, we could model the point as a list:
point = [2.5, 6]
print("In", point, "the x coordinate is", point[0])
or as a tuple:
point = (2.5, 6)
print("In", point, "the x coordinate is", point[0])
For both Output: the x coordinate is 2.5
Q. 12 handling exceptions.
Python provides a standard mechanism called exception handling that allows
programmers to deal with these kinds of run-time errors and many more. Rather
than always terminating the program’s execution, a program can detect the
problem and execute code to correct the issue or manage it in other ways.
Python’s exception handling infrastructure allows programmers to cleanly
separate the code that implements the algorithm with exceptional situations
that the algorithm may face. This approach is more modular and encourages the
development of code that is cleaner and easier to maintain and debug.
Q 12.1 An exception is a special object that the executing program can create
when it encounters an extraordinary situation. Such a situation almost always
represents a problem, usually some sort of run-time error. Examples of
exceptional situations include:
• Attempting to read past the end of a file
• Evaluating the expression list[i] where list is a list, and i > len(list).
• Attempting to convert a non-numeric string to a number, as in int("Fred")
• Attempting to read data from the network when the connection is lost.
Exceptions represent a standard way to deal with run-time errors. In
programming languages that do not support exception handling, programmers
must devise their own ways of dealing with exceptional situations. One common
approach is for functions to return an integer code that represents success or
failure.
List of Standard Exceptions –
Exception : Base class for all exceptions
OverflowError: Raised when a calculation exceeds maximum limit for integers
FloatingPointError: Raised when a floating point calculation fails
ZeroDivisionError: Raised when division or modulo by zero takes place
EOFError: Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
NameError: Raised when an identifier is not found in the local or global
namespace.
IndentationError: Raised when indentation is not specified properly.
UnboundLocalError: Raised when trying to access a local variable in a function or
method but no value has been assigned to it.
ValueError: Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
E.g.
x = int(input("Please enter a small positive integer: "))
print("x =", x)
Output: Please enter a small positive integer: Five
# If the user enters “Five,” this code results in the run-time environment reporting
a ValueError exception before killing the program.
#We can wrap this code in a try/except construct as
try:
x = int(input("Please enter a small positive integer: "))
print("x =", x)
except ValueError:
print("Input cannot be parsed as an integer")
Output: Please enter a small positive integer: Five
Input cannot be parsed as an integer
Output: Please enter a small positive integer: 5
5
a = [1, 2, 3]
try:
print( "Second element =" , a[1])
print ("Fourth element = " ,a[3])
# error since there are only 3 elements
except IndexError:
print ("An error occurred")
Output: Second element = 2
An error occurred
try :
a = 3
if a < 4 :
b = a/(a-3)
print ("Value of b = ", b)
# throws ZeroDivisionError for a = 3
# There is no variable b declared, so throws NameError if a >= 4
Except (ZeroDivisionError, NameError):
print ("Error Occurred and Handled")
Output: Error Occurred and Handled

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python functions
Python functionsPython functions
Python functions
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python
PythonPython
Python
 
NUMPY
NUMPY NUMPY
NUMPY
 
Python set
Python setPython set
Python set
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Functions in C
Functions in CFunctions in C
Functions in C
 

Ähnlich wie Python Unit 5 Questions n Notes.pdf

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
Python data type
Python data typePython data type
Python data typeJaya Kumari
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_pythondeepalishinkar1
 
Python list manipulation basics in detail.pdf
Python list  manipulation basics in detail.pdfPython list  manipulation basics in detail.pdf
Python list manipulation basics in detail.pdfneonaveen
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfAsst.prof M.Gokilavani
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptxChandanVatsa2
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docxmanohar25689
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonchanna basava
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear listsToniyaP1
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptxSakith1
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 

Ähnlich wie Python Unit 5 Questions n Notes.pdf (20)

Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Python data type
Python data typePython data type
Python data type
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
Python list manipulation basics in detail.pdf
Python list  manipulation basics in detail.pdfPython list  manipulation basics in detail.pdf
Python list manipulation basics in detail.pdf
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 

Kürzlich hochgeladen

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Kürzlich hochgeladen (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Python Unit 5 Questions n Notes.pdf

  • 1. MODULE V: LINEAR SEARCH Q.1 what are Lists A list in Python is an ordered group of items or elements. It's important to notice that these list elements don't have to be of the same type. It can be an arbitrary mixture of elements like numbers, strings, and other lists and so on. A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. The main properties of Python lists: • They are ordered • The contain arbitrary objects • Elements of a list can be accessed by an index • They are arbitrarily nestable, i.e. they can contain other lists as sub-lists • Variable size • They are mutable, i.e. the elements of a list can be changed List Description [ ] An empty list [1,1,2,3,5,8] A list of integers [42, "What's the question?", 3.1415] A list of mixed data types [ "Riyas", "Priya", "Zubair", "Manazir", " Ibrahim" ] A list of Strings [ ["Chennai","Tamilnadu", 600048], ["Hyderabad","Telangana",5000321 ] ] A nested list
  • 2. Q1.1 What are the various List Methods available in Python? Methods that are available with list object in Python programming are tabulated below. They are accessed as list.Method (). Some of the methods are as follows: Python List Methods insert() - Insert an item at the defined index index() - Returns the index of the first matched item append() - Add an element to the end of the list extend() - Add all elements of a list to the another list remove() - Removes an item from the list clear() - Removes all items from the list copy() - Returns a shallow copy of the list reverse() - Reverse the order of items in the list sort() - Sort items in a list in ascending order count() - Returns the count of number of items passed as an argument pop() - Removes and returns an element at the given index Q.2 How to do List Assignment. A list refers to a collection of objects; it represents an ordered sequence of data. In that sense, a list is similar to a string, except a string can hold only characters. We may access the elements contained in a list via their position within the list. A list need not be homogeneous; that is, the elements of a list do not all have to be of the same type. Like any other variable, a list variable can be local or global, and it must be defined (assigned) before it is used.
  • 3. The following code fragment declares a list named list that holds the integer values 2,−3,0,4,−1: List = [2, -3, 0, 4, -1] The right-hand side of the assignment statement is a literal list. The elements of the list appear within square brackets [ ], the elements are separated by commas. The following statement: a = [] # assigns the empty list to a. We can print list literals and lists referenced through variables: List = [2, -3, 0, 4, -1] # Assign the list print ([2, -3, 0,4,-1]) # Print a literal list print (List) # Print a List variable List = [2, -3, 0, 4, -1] # Assign the list List [0] = 5 # Make the first element 5 print(List [1]) # Print the second element -3 List [4] = 12 # Make the last element 12 print (List) # Print a list variable print( [10, 20, 30] [1] ) # Print 2nd element of list Q.3 List Bounds. In the following code fragment: a = [10, 20, 30, 40] All of the following expressions are valid: a[0], a[1], a[2] and a[3]. The expression a[4] does not represent a valid element in the list. print (a[4]) # Out-of-bounds access An attempt to use above expression, as in a = [10, 20, 30, 40] results in a run- time exception. The interpreter will insist that the programmer use an integral value for an index, but in order to prevent a run-time exception the programmer must ensure that the index used is within the bounds of the list.
  • 4. A negative list index represents a negative offset from an imaginary element one past the end of the list. For list lst, the expression element in lst and The expression so forth. Q. 4 Slicing. We can make a new list from a portion of an existing list using a technique known as slicing. A list slice is an expression of the form where • list is a list of variable referring to a list object, a literal list, or some other expression that evaluates to a list. • begin is an integer representing the starting index of the list. • end is an integer that is one larger than the index of the last element in a subsequence of the list. We can access a range of items in a list by using the Slicing can be best visualized by con elements as shown below. So if we want to access a range, we need two indices that will slice that portion from the list My_List = ['p', print(My_list [ 2:5 ] ) print(My_list [: -5] ) print(My_list[5:]) print(My_list[:]) A negative list index represents a negative offset from an imaginary element one For list lst, the expression lst[-1] represents the The expression lst[-2] represents the next to last element We can make a new list from a portion of an existing list using a technique known an expression of the form list [begin: end]. is a list of variable referring to a list object, a literal list, or some other expression that evaluates to a list. is an integer representing the starting index of a subsequence of is an integer that is one larger than the index of the last element in a subsequence of the list. We can access a range of items in a list by using the slicing operator 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 two indices that portion from the list List = ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z' ] Output : ['O', 'G', 'R'] Output : ['P', 'R', 'O', 'G'] Output : ['A', 'M', 'I', 'Z'] Output : ['P', 'R', 'O', 'G', 'R', 'A', 'M', 'I', 'Z'] A negative list index represents a negative offset from an imaginary element one represents the last next to last element, and We can make a new list from a portion of an existing list using a technique known is a list of variable referring to a list object, a literal list, or some other a subsequence of is an integer that is one larger than the index of the last element in a slicing operator (colon). sidering the index to be between the elements as shown below. So if we want to access a range, we need two indices ['P', 'R', 'O', 'G', 'R', 'A', 'M', 'I', 'Z']
  • 5. Q.5 List and Functions. A list can be passed to a function, since list objects are mutable; passing to a function a reference to a list object binds the formal parameter to the list object. This means the formal parameter becomes an alias of the actual parameter. The change_list method does attempt to modify list parameter. This means the clear function will modify the list object outside function. Eg.1 Passing Immutable Object (List) def change_list(list1): list1.append(5); list1.append(6); print("list inside function = ",list1) #defining the list list1 = [1, 2, 3, 4] change_list (list1); # function call print ("list outside function = ", list1); Output: list inside function = [1,2,3,4,5,6] list outside function = [1,2,3,4,5,6] Q. 6 Prime Generation with List. fasterprimes.py uses an algorithm developed by the Greek mathematician Eratosthenes who lived from 274 B.C. to 195 B.C. Called the Sieve of Eratosthenes, the principle behind the algorithm is simple: • Make a list of all the integers two and larger. • Two is a prime number, but any multiple of two cannot be a prime number (since a multiple of two has two as a factor). • Go through the rest of the list and mark out all multiples of two (4, 6, 8 ...). • Move to the next number in the list (in this case, three). If it is not marked out, it must be prime, so go through the rest of the list and mark out all multiples of that number (6, 9, 12,..........).
  • 6. • Continue this process until you have listed all the primes you want. Fast prime fasterprimes.py implements the Sieve of Eratosthenes def primes(n): if n==2: return [2] elif n<2: return [] s=range(3,n+1,2) mroot = n ** 0.5 half=(n+1)/2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)/2 s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i+3 return [2]+[x for x in s if x] print primes(13) Output : [2, 3, 5, 7, 11, 13] print primes(100) Output : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
  • 7. Q.7 what is sorting? Arranging the elements within a list into a particular order is a common activity. For example, a list of integers may be arranged in ascending order (that is, from smallest to largest). Many sorting algorithms exist, and some perform much better than others. We will consider one sorting algorithm that is relatively easy to implement. The selection sort algorithm is relatively easy to implement and easy to understand how it works. 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 sub-arrays in a given array. 1) The sub-array which is already sorted. 2) Remaining sub-array which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted sub-array is picked and moved to the sorted sub-array. import sys A = [64, 25, 12, 22, 11] for i in range(0, len(A)): # Traverse through all array elements for j in range (i+1, len(A)): if A[i] > A[j]: # comparing 1st element with 2nd, 3rd n so on Temp = A[i] # Swap the minimum element with the first element A[i] = A[j] A[j] = Temp print ("Sorted array n ") for i in range(0, len(A)): print("%d" %A[i])
  • 8. Q What is Flexible sorting. Consider a situation where we want the behaviour of the sorting function in so that it arranges the elements in descending order instead of ascending order. This situation can be easily achieved by simply changing the line if list[j] < list[small]: # for Ascending order to be if list[j] > list[small]: # for Descending order But consider a situation where we want to change the sort so that it sorts the elements in ascending order or descending order without changing the if condition again and again. Therefore, in order to make our function more flexible we will pass an ordering function as a parameter of functions as parameters to other functions and arranges the elements in a list two different ways using the same selection_sort function. def less_than(m, n): return m < n def greater_than(m, n): return m > n def selection_sort(list, comp): n = len(list) for i in range(n - 1): small = i for j in range(i + 1, n): if comp ( list[j], list[small] ): small = j if i != small: list[i],list[small] = list[small], list[i] Original_List = [5,1,9,22,6,33,7] working = Original_List[:] selection_sort (working, less_than) print('Ascending: ', working) selection_sort (working, greater_than) print('Descending:', working) Output: Ascending: [1, 5, 6, 7, 9, 22, 33] Descending: [33, 22, 9, 7, 6, 5, 1]
  • 9. Q. 8 Searching Basics: Searching is a very basic necessity when you store data in different data structures. Searching a list for a particular element is a common activity.The simplest approach is to go across every element in the data structure and match it with the value you are searching for. This is known as linear search. It is inefficient and rarely used, but creating a program for it gives an idea about how we can implement some advanced search algorithms We examine two basic strategies: linear search and binary search. In Linear search is a sequential search is made over all items one by one for finding a particular value among list of items. It starts searching the value from the beginning of the list and continues till the end of the list until the value is found. def linear_search (values, search_elm): search_at = 0 # search_at will give position or index of item res = False # res will signal whether search is successful or not while search_at < len(values) and res is False: if values[search_at] == search_elm: # search_elm is item to search res = True else: search_at = search_at + 1 # increment index return res list = [64, 34, 25, 12, 22, 11, 90] print(linear_search(list, 12)) print(linear_search(list, 91)) Output: True False
  • 10. Binary search is an algorithm for locating the position of an item in a sorted array. Linear search is acceptable for relatively small lists, but the process of examining each element in a large list is time consuming. An alternative to linear search is binary search. In order to perform binary search, a list must be in sorted order. Binary search exploits the sorted structure of the list using a clever but simple strategy that quickly zeros in on the element to find: • If the list is empty, return none. • Compare x with the middle element, If x matches with middle element, we return the mid index. • If the middle element is larger than the element you are seeking, perform a binary search on the left first half of the list. • If the middle element is smaller than the element you are seeking, perform a binary search on the right half of the list. def binary_search (List, L, U, elm): if U >= L: # Check U as Upper Bound mid = int (L + (U - L)/2) # convert into integer if List[mid] == elm: # If element is at mid return mid elif List [mid] > x: # If elm is smaller return binary_search(List, L, mid-1, elm) else: return binary_search(List, mid+1, U, elm) else: return -1 # Element not present in List List = [ 2, 3, 4, 10, 40 , 70, 100] x = int ( input(“Enter search element:”)) result = binary_search (list, 0, len(list)-1, x) if result != -1: print ("Element present at index" result ) else: print ("Element is not present in list") Output: Enter search element: 10 Element present at index 3
  • 11. Q. 9 List Permutation Sometimes it is useful to consider all the possible arrangements of the elements within a list. Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very important. The number of permutations on a set of n elements is given by n! . For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}. To test a permutation function, a programmer could check to see to see if it produces the correct result for all arrangements of a relatively small list. Below program generates all the permutations of a given list. def permutation(list): if len(list) == 0: # If list is empty then there are no permutations return [] if len(list) == 1: # If one element in list then, only one permutation return [list] Cur_list = [] # empty list that will store permutation for i in range(len(list)): # Iterate the input(list) and calculate the permutation first_elm = list[i] remlist = list[: i] + list[i+1:] # Extract remaining list from the list for p in permutation(remlist): Cur_list.append ([first_elm] + p) return Cur_list data =[1,2,3] # Program will start here for p in permutation(data): print (p)
  • 12. Another Method of Generating Permutations using standard functions. Q.9.1 Random Permutation We can generate all the permutations of a list in an orderly fashion. Often, however, we need to produce one those permutations chosen at random. For example, we may need to randomly rearrange the contents of an ordered list so that we can test a sort function to see if it will produce the original list. We could generate all the permutations, put each one in a list, and select a permutation at random from that list. This approach is inefficient, especially as the length of the list to permute grows larger. Fortunately, we can randomly permute the contents of a list easily and quickly. from random import randrange def permute(lst): #Randomly permutes the contents of list lst n = len(lst) for i in range(n - 1): pos = randrange(i, n) # i <= pos < n lst[i], lst[pos] = lst[pos], lst[i] a = [1, 2, 3, 4, 5, 6, 7, 8] print('Before:', a) permute(a) print('After :', a) import itertools List = [1, 2, 3] # 3! Or 6 permutation can be formed permutations_object = itertools.permutations(List) # Find permutations of List permutations_List = List(permutations_object) # Create list from permutations print(permutations_List) Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] Output: Before: [1, 2, 3, 4, 5, 6, 7, 8] After : [4, 6, 1, 7, 8, 3, 5, 2] After : [3, 5, 1, 6, 8, 7, 2, 4]
  • 13. Q.10 What are Objects. Python is an object oriented programming language and almost everything in Python is an object, with its properties and methods. A Class is like an object blueprint for creating objects. Classes provide a means of bundling data and functionality together. E.g. The assignment statement x = 2 Binds the variable x to an integer object with the value of 2. The name of the class of object x is int. An object is an instance of a class which fuse data and functions together. A typical object consists of two parts: data and methods. An object’s data is sometimes called its attributes or fields. Methods are like functions, and they also are known as operations. The data and methods of an object constitute its members. Using the same terminology as functions, the code that uses an object is called the object’s client. Just as a function provides a service to its client, an object provides a service to its client. The services provided by an object can be more elaborate that those provided by simple functions, because objects make it easy to store persistent data. In python a class is created by the keyword class. E.g. Create a class named My_Class, with a property named x: class My_Class: # Creating Class x = 5 obj1 = My_Class() # Creating an Object print(obj1.x) Output: 5 class Person: def __init__ (self, name, age): self.name = name self.age = age per1 = Person("Durga", 21) print(per1.name, per1.age) Output: Durga 21
  • 14. class My_Class: a = 10 def fun(self) : print('Hello') ob1 = My_Class() # create a new My_Class object ob1 ob.fun() # calling fun with no parameter Output : Hello class Person: def__init__(myobj, name, age): myobj.name = name myobj.age = age def myfunc (p): print("my name is " + p.name) per1 = Person("Durga", 21) per1.myfunc() Output : My name is Durga The __init__() function is called automatically every time the class is being used to create a new object. The self parameter is a reference to the current instance (per1) of the class, and is used to access variables that belong to the class. It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of any function in the class: Q. String objects Strings are like lists is some ways because they contain an ordered sequence of elements. Strings are distinguished from lists in three key ways: • Strings must contain only characters, while lists may contain objects of any type. • Strings are immutable. The contents of a string object may not be changed. Lists are mutable objects.
  • 15. • If two strings are equal with == comparison, they automatically are aliases (equal with the is operator). This means two identical string literals that appear in the Python source code refer to the same string object. E.g. word1 = 'Wow' word2 = 'Wow' print('Equality:', word1 == word2, ' Alias:', word1 is word2) Output : Equality: True Alias: True We assign word1 and word2 to two distinct string literals. Since the two string literals contain exactly the same characters, the interpreter creates only one string object. The two variables word1 and word2 are bound to the same object. We say the interpreter merges the two strings. Since in some programs strings may be long, string merging can save space in the computer’s memory. Strings Methods Upper : Returns a copy of the original string with all the characters converted to uppercase Lower: Returns a copy of the original string with all the characters converted to lower case Center: Returns a copy of the string centred within a string of a given width and optional fill characters; fill characters default to spaces Count : Determines the number times the string parameter is found as a substring; the count includes only non-overlapping occurrences Find : Returns the lowest index where the string parameter is found as a substring; returns −1 if the parameter is not a substring E.g name = input("Please enter your name: ") print("Hello " + name.upper() + ", how are you?") Output: Please enter your name: Zamir Hello ZAMIR, how are you?
  • 16. The expression name. upper() within the print statement represents a method call. The general form of a method call is object.methodname (parameterlist) • object is an expression that represents object and name is a reference to a string object. • The period, pronounced dot, associates an object expression with the method to be called. • methodname is the name of the method to execute. • The parameterlist is comma-separated list of parameters to the method. For some methods the parameter list may be empty, but the parentheses always are required Q. List objects • A list is a data-structure, or it can be considered a container that can be used to store multiple data at once. • The list will be ordered and there will be a definite count of it. • The elements are indexed according to a sequence and the indexing is done with 0 as the first index. • Each element will have a distinct place in the sequence and if the same value occurs multiple times in the sequence, each will be considered separate and distinct element. We assigned lists, passed lists to functions, returned lists from functions, and interacted with the elements of lists.
  • 17. Since lists are mutable data structures, the list class has both __getitem__ and __setitem__ methods. The statement x = lst[2] behind the scenes becomes the method call x = list.__getitem__(lst, 2) and the statement lst[2] = x maps to list.__setitem__(lst, 2, x) The code lst = ["one", "two", "three"] lst += ["four"] is same as lst.append("four") print(lst) Output : ['one', 'two', 'three', 'four'] Few methods available to List objects are... Count: Returns the number of times an element appears in the list. Does not modify the list. Insert: Inserts a new element before the element at a given index. Increases the length of the list by one and also Modifies the list. Append: Adds a new element to the end of the list. Modifies the list. Remove: Removes the first occurrence (lowest index) of a given element from the list. Index Produces an error if the element is not found. Modifies the list if the item to remove is in the list. Reverse: Physically reverses the elements in the list. The list is modified.
  • 18. Sort: Sorts the elements of the list in ascending order. The list is modified Index: Returns the lowest index of a given element within the list. Produces an error if the element does not appear in the list. Does not modify the list. Q. 11 Geometric, To introduce simple objects, consider two-dimensional geometric points from mathematics. We consider a single point object to consist of two real number coordinates: x and y. We ordinarily represent a point by an ordered pair (x,y). In a program, we could model the point as a list: point = [2.5, 6] print("In", point, "the x coordinate is", point[0]) or as a tuple: point = (2.5, 6) print("In", point, "the x coordinate is", point[0]) For both Output: the x coordinate is 2.5 Q. 12 handling exceptions. Python provides a standard mechanism called exception handling that allows programmers to deal with these kinds of run-time errors and many more. Rather than always terminating the program’s execution, a program can detect the problem and execute code to correct the issue or manage it in other ways. Python’s exception handling infrastructure allows programmers to cleanly separate the code that implements the algorithm with exceptional situations that the algorithm may face. This approach is more modular and encourages the development of code that is cleaner and easier to maintain and debug. Q 12.1 An exception is a special object that the executing program can create when it encounters an extraordinary situation. Such a situation almost always
  • 19. represents a problem, usually some sort of run-time error. Examples of exceptional situations include: • Attempting to read past the end of a file • Evaluating the expression list[i] where list is a list, and i > len(list). • Attempting to convert a non-numeric string to a number, as in int("Fred") • Attempting to read data from the network when the connection is lost. Exceptions represent a standard way to deal with run-time errors. In programming languages that do not support exception handling, programmers must devise their own ways of dealing with exceptional situations. One common approach is for functions to return an integer code that represents success or failure. List of Standard Exceptions – Exception : Base class for all exceptions OverflowError: Raised when a calculation exceeds maximum limit for integers FloatingPointError: Raised when a floating point calculation fails ZeroDivisionError: Raised when division or modulo by zero takes place EOFError: Raised when there is no input from either the raw_input() or input() function and the end of file is reached. NameError: Raised when an identifier is not found in the local or global namespace. IndentationError: Raised when indentation is not specified properly.
  • 20. UnboundLocalError: Raised when trying to access a local variable in a function or method but no value has been assigned to it. ValueError: Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. E.g. x = int(input("Please enter a small positive integer: ")) print("x =", x) Output: Please enter a small positive integer: Five # If the user enters “Five,” this code results in the run-time environment reporting a ValueError exception before killing the program. #We can wrap this code in a try/except construct as try: x = int(input("Please enter a small positive integer: ")) print("x =", x) except ValueError: print("Input cannot be parsed as an integer") Output: Please enter a small positive integer: Five Input cannot be parsed as an integer Output: Please enter a small positive integer: 5 5
  • 21. a = [1, 2, 3] try: print( "Second element =" , a[1]) print ("Fourth element = " ,a[3]) # error since there are only 3 elements except IndexError: print ("An error occurred") Output: Second element = 2 An error occurred try : a = 3 if a < 4 : b = a/(a-3) print ("Value of b = ", b) # throws ZeroDivisionError for a = 3 # There is no variable b declared, so throws NameError if a >= 4 Except (ZeroDivisionError, NameError): print ("Error Occurred and Handled") Output: Error Occurred and Handled