Python Notes Unit 5
Python Notes Unit 5
Python Notes Unit 5
Iterators in Python
Iterator in python is any python type that can be used with a ‘for in loop’. Python lists,
tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators
because they implement following methods. In fact, any object that wants to be an
iterator must implement following methods.
1. __iter__ method that is called on initialization of an iterator. This should return
an object that has a next or __next__ (in Python 3) method.
2. next ( __next__ in Python 3) The iterator next method should return the next
value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop
implicitly calls next() on the iterator object. This method should raise a
StopIteration to signal the end of the iteration.
Below is a simple Python program that creates iterator type that iterates from 10 to
given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5,
then it prints nothing.
# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
# Constructor
def __init__(self, limit):
self.limit = limit
# Prints nothing
for i in Test(5):
print(i)
Output :
10
11
12
13
14
15
We know that in Python, a function can call other functions. It is even possible for
the function to call itself. These type of construct are termed as recursive
functions.
Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Each function call multiples the number with the factorial of number 1 until the number
is equal to one.
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The
objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:
if n == 1:
return
# Driver code
n=4
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
The program takes a list and key as input and finds the index of the key in the list using
linear search.
Problem Solution
Here is the source code of a Python program to implement linear search. The program
output is shown below.
def linear_search(alist, key):
"""Return index of key in alist. Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1
Program Explanation
Case 1:
Enter the list of numbers: 5 4 3 2 1 10 11 2
The number to search for: 1
1 was found at index 4.
Case 2:
Enter the list of numbers: 5 2 1 5 -3
The number to search for: 2
2 was found at index 1.
Case 3:
Enter the list of numbers: 3 5 6
The number to search for: 2
2 was not found.
Problem Description
The program takes a list and key as input and finds the index of the key in the list using
binary search.
Problem Solution
Here is the source code of a Python program to implement binary search without using
recursion. The program output is shown below.
def binary_search(alist, key):
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
mid = (start + end)//2
if alist[mid] > key:
124 | P a g e Python Programming (KNC-302)
end = mid
elif alist[mid] < key:
start = mid + 1
else:
return mid
return -1
Program Explanation
Case 1:
Enter the sorted list of numbers: 3 5 10 12 15 20
The number to search for: 12
12 was found at index 3.
Case 2:
Enter the sorted list of numbers: -3 0 1 5 6 7 8
The number to search for: 2
2 was not found.
Case 3:
Enter the sorted list of numbers: 5
The number to search for: 5
5 was found at index 0.
Here is the source code of a Python program to implement selection sort. The program
output is shown below.
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
Program Explanation
Case 1:
Enter the list of numbers: 3 1 4 5 2 6
Case 2:
Enter the list of numbers: 2 10 5 38 1 7
Sorted list: [1, 2, 5, 7, 10, 38]
Case 3:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]
1. Create a function merge_sort that takes a list and two variables start and end as
arguments.
2. The function merge_sort will sort the list from indexes start to end – 1 inclusive.
3. If end – start is not greater than 1, then return.
4. Otherwise, set mid equal to the floor of (start + end)/2.
5. Call merge_sort with the same list and with start = start and end = mid as
arguments.
6. Call merge_sort with the same list and with start = mid and end = end as
arguments.
7. Call the function merge_list, passing the list and the variables start, mid and end as
arguments.
8. The function merge_list takes a list and three numbers, start, mid and end as
arguments and assuming the list is sorted from indexes start to mid – 1 and from mid
to end – 1, merges them to create a new sorted list from indexes start to end – 1.
Program/Source Code
Here is the source code of a Python program to implement merge sort. The program
output is shown below.
def merge_sort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)
Program Explanation
Case 1:
Enter the list of numbers: 3 1 5 8 2 5 1 3
Sorted list: [1, 1, 2, 3, 3, 5, 5, 8]
Case 2:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]
Case 3:
Enter the list of numbers: 1
Sorted list: [1]
sorted
sorted does pretty much the same thing what you expected.
# sorting numbers
In [0]: sorted([9, 5, 7])
Out[0]: [5, 7, 9]
# sorting alphabetically
In [0]: sorted(['foo', 'bar'])
Out[0]: ['bar', 'foo']