0% found this document useful (0 votes)
60 views

Unit 4 Notes

This document provides information on lists in Python. It defines lists as collections of elements separated by commas and enclosed in square brackets. It describes how to create and access list elements using indexes, and lists various list methods like append(), insert(), remove(), pop(), clear(), index(), count(), and sort(). List operations like length, concatenation, repetition, membership, slicing and iteration are also covered.

Uploaded by

SUGANYA N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Unit 4 Notes

This document provides information on lists in Python. It defines lists as collections of elements separated by commas and enclosed in square brackets. It describes how to create and access list elements using indexes, and lists various list methods like append(), insert(), remove(), pop(), clear(), index(), count(), and sort(). List operations like length, concatenation, repetition, membership, slicing and iteration are also covered.

Uploaded by

SUGANYA N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT 4 LIST, TUPLES AND DICTIONARIES

LIST:
List is a collection of sequence of elements within square brackets[], separated by comma(,).

Creating a list:
A list is created by putting the values inside the square brackets separated by commas.
List indices start at 0
Eg:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

Accessing Values in Lists


An element in a list can be accessed through index operator([ ]).
Syntax:

Listname[index_value]

For example
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[5]: ", list2[5])

Output:
list1[0]: physics
list2[5]: 6

Types of indexing:

1.Forward indexing: indexing value starts from left and goes through right.

Eg:

S a m m y S h a r k !
0 1 2 3 4 5 6 7 8 9 10 11

2.Reverse indexing: indexing value starts from right and goes through left.

S a m m y S h a r k !
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

List Length:

This function returns the length of a list which is equal to number of elements.
Updating Lists
List can be updated by using indexing.
Eg:
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Output:
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements
To remove a list element, you can use either the del statement
Eg:
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

Operations

S,No Operation Description Python Results


Expression

1 Length Gives the total length(number of a=[1,2,3] 3


elements) of the list. print(len(a))

2 Concatenation Combines two different lists a=[1,2,3];b=[4, [1, 2, 3,


5,6] 4, 5, 6]
print(c=a+ b]

3 Repetition Repeats the elements in the list a=['Hi!'] ['Hi!',


print(a*4) 'Hi!',
'Hi!',
'Hi!']

4 Membership Says if the element is in the list or not a=[1, 2, 3]


3 in a True
5 not in a True
5 Iteration process wherein a set of instructions or for x in [1, 2, 123
structures are repeated in a sequence a 3]: print x,
specified number of times or until a
condition is met

6 Slice We can access a range of items in a list my_list = ['o', 'g',


by using the slicing operator (colon). ['p','r','o','g','r','a 'r']
','m','i','z']
# elements 3rd
to 5th
print(my_list[2
:5])

Methods

S.
Method
No Description Syntax Example Output

Add an element List.append(item) animal = ['cat', 'dog', Updated


to the end of the 'rabbit'] animal list:
list # an element is added ['cat', 'dog',
1 append() animal.append('guinea 'rabbit',
pig') 'guinea pig']
#Updated Animal List
print('Updated animal list:
', animal)
Add all List.extend(list1) language = ['French', Language
elements of a 'English', 'German'] List:
list to the # another list of language ['French',
another list language1 = ['Spanish', 'English',
2 extend() 'Portuguese'] 'German',
language.extend(language 'Spanish',
1) 'Portuguese'
# Extended List ]
print('Language List: ',
language)
Insert an item at List.insert(index, vowel = ['a', 'e', 'i', 'u'] Updated
the defined item) # inserting element to list List: ['a', 'e',
3 insert() index at 4th position 'i', 'o', 'u']
vowel.insert(3, 'o')
print('Updated List: ',
vowel)
Removes an List.remove(elem # animal list Updated
item from the ent) animal = ['cat', 'dog', animal list:
list 'rabbit', 'guinea pig'] ['cat', 'dog',
4 remove() # 'rabbit' element is 'guinea pig']
removed
animal.remove('rabbit')
#Updated Animal List
print('Updated animal list:
', animal)
Removes and List.pop(index) # programming language Updated
returns an list List:
element at the language = ['Python', ['Python',
given index 'Java', 'C++', 'French', 'C'] 'Java', 'C++',
5 pop() # Return value from pop() 'C']
return_value =
language.pop(3)
# Updated List
print('Updated List: ',
language)
Removes all List.clear() list = [{1, 2}, ('a'), ['1.1', List: []
items from the '2.2']]
6 clear() list # clearing the list
list.clear()
print('List:', list)
Returns the List.index(elemen vowels = ['a', 'e', 'i', 'o', 'i', The index
index of the t) 'u'] of e: 1
first matched # element 'e' is searched
7 index() item index = vowels.index('e')
# index of 'e' is printed
print('The index of e:',
index)
Returns the List.count(elemen vowels = ['a', 'e', 'i', 'o', 'i', The count
count of t) 'u'] of i is: 2
number of items # count element 'i'
8 count() passed as an count = vowels.count('i')
argument # print count
print('The count of i is:',
count)
Sort items in a List.sort() vowels = ['e', 'a', 'u', 'o', 'i'] Sorted list:
list in ascending # sort the vowels ['a', 'e', 'i',
9 sort() order vowels.sort() 'o', 'u']
# print vowels
print('Sorted list:', vowels)
Reverse the List.reverse() a=[10,30,30,40,50] Reverse:[50,
10 reverse() order of items print(“Reverse:”a.reverse( 40,30,30,10]
in the list ))

Returns a new_list=old_list. old_list = [1, 2, 3] new_list: [1,


11 copy() shallow copy of copy() new_list = old_list.copy() 2, 3]
the list print(“new list:”,
new_list)
It takes two range(a,b) range(1,5) [1,2,3,4]
arguments as range(10) [0,1,2,3,4,5,
12 Range() input and 6,7,8,9]
returns the list range(1,10,2) [1,3,5,7,9]
of elements
within the range
List loop:
It has the ability to iterate over the items of any sequence.
Syntax
for iterating_var in sequence:
statements(s)
Flow Diagram

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence
is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each
item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.
Example
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

Iterating by Sequence Index


An alternative way of iterating through each item is by index offset into the sequence itself.
Eg:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!"

Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

Using else Statement with Loops


Python supports to have an else statement associated with a loop statement
 If the else statement is used with a for loop, the else statement is executed when the loop
has exhausted iterating the list.
 If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
Eg: Live Demo
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
Output:
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

Aliasing:
If we assign one variable to another, bother variables refer to same object.
>>a=[1,2,3]
>>a=b
>>a is b
True
Here the same list have two different names, a and b. if any changes made in one list ‘a’ will
affect the other list ‘b’.

Cloning:
If we want to modify the list, want to keep a copy of the original list.
Slice operator is used for cloning a list.
Eg:
>>a=[1,2,3]
>>b=a[:]
>>print(b)
Output:
[1,2,3]
If any changes made in one list, will not affect the other.

Tuples:
Tuple is a sequence of elements written within paranthesis () and separated by comma(,).
It is immutable,

Creating a tuple
A tuple is created by putting the values inside the paranthesis separated by commas.
Eg:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

Accessing Values in tuple


An element in a list can be accessed through index operator([ ]).
Syntax:
tuplename[index_value]
Eg:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
Output:
tup1[0]: physics

Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements.
You are able to take portions of existing tuples to create new tuples

Eg:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print (tup3)
Output:
(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible.

Remove an entire tuple by using the del statement.


Eg:
tup = ('physics', 'chemistry', 1997, 2000)
print (tup)
del tup
print ("After deleting tup : ")
print (tup)

Output:
('physics', 'chemistry', 1997, 2000)

After deleting tup :


Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined

Operations:

S,No Operation Description Python Results


Expression

1 Length Gives the total length(number of a=[1,2,3] 3


elements) of the list. print(len(a))

2 Concatenation Combines two different lists a=[1,2,3];b=[4, [1, 2, 3,


5,6] 4, 5, 6]
print(c=a+ b]

3 Repetition Repeats the elements in the list a=['Hi!'] ['Hi!',


print(a*4) 'Hi!',
'Hi!',
'Hi!']

4 Membership Says if the element is in the list or not a=[1, 2, 3]


3 in a True
5 not in a True

5 Slice We can access a range of items in a list my_list = ['o', 'g',


by using the slicing operator (colon). ['p','r','o','g','r','a 'r']
','m','i','z']
# elements 3rd
to 5th
print(my_list[2
:5])
Tuple functions:

S.No. functions Syntax Function with Description Example Output

1 Comparison cmp(tuple1, Compares elements of both tuple1 = ('python', 'geek') Not the same
tuple2) tuple2 = ('coder', 1)
tuples. if (cmp(tuple1, tuple2) !=
0):
# cmp() returns 0 if
matched, 1 when not
tuple1
# is longer and -1 when
tuple1 is shoter
print('Not the same')
else:
print('Same')

2 Length len(tuple) Gives the total length of the tuple2 = ('python', 'geek') 2
print(len(tuple2))
tuple.

3 Maximum max(tuple) Returns item from the tuple Maximum element in


value tuple1 = ('python', 'geek') tuples 1,2:
with max value. tuple2 = ('coder', 1) python,coder
print ('Maximum element
in tuples 1,2: ' +
str(max(tuple1)) + ','
+
str(max(tuple2)))

4 Minimum min(tuple) Returns item from the tuple tuple1 = ('python', 'geek') Minimum element in
value tuple2 = ('coder', 1) tuples 1,2: geek,1
with min value. print ('Minimum element
in tuples 1,2: ' +
str(min(tuple1)) + ',' +
str(min(tuple2)))

5 Conversion tuple(seq) Converts a list into tuple. list1 = [0, 1, 2] (0, 1, 2)


of list into print(tuple(list1))
('p', 'y', 't', 'h', 'o', 'n')
tuple print(tuple('python'))
Dictionary:

 A dictionary is a container object that stores a collection of key: value pairs.


 It ensures fast retrieval, deletion and updating of value by using a key.
 It is mutable and unordered collection.
 Key is like an index operator.

Keys Values

Key/Index value 1 Value1

Key/Index value 2 Value1

Key/Index value 3 Value1

Structure of Dictionary

Creating a dictionary:

There are two ways in creating a dictionary. They are,

1. It can be created by specifying the key and value separated by a colon(:) and the pair is

separated by commas. The elements are enclosed within curly braces.

Fruits={1:apple,2:orange,3:grapes}

2. Another way is to use dict() constructor that is used o create a dictionary.

Fruits:{}

Characteristics of a dictionary:

1. Dictionary is mutable(we can add/delete/update values).

2. They are unordered set of key: value pairs.

3. Dictionary is not in sequence memory location.

4. Each key in the dictionary is unique.

Operations in dictionary:

i) Creating a dictionary:
There are two ways in creating a dictionary. They are,

1. Another way is to use dict() constructor that is used o create a dictionary.

months={}

2. It can be created by specifying the key and value separated by a colon(:) and the pair is

separated by commas. The elements are enclosed within curly braces.

Eg:

months = { 1 : "January", 2 : "February", : "March", 4 : "April", 5 : "May", 6 : "June",


7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November",12 : "December" }
# months[1-12] are keys and "January-December" are the values
print ("The dictionary contains the following keys: ", months.keys())
Output:
The dictionary contains the following keys: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11, 12]

Accessing a dictionary:
1. Adding an aelement
2. Updating the element
3. Deleting the element
4. Checking for presence of key

1. Adding an element:
To add a new element to a dictionary, assign a value to a new key.
Syntax:
Dictionary_name[new_key-value]=value

Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June", 7 :
"July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

months[12]=December # add new key and value


print (“After adding”,months)

Output:

After adding: {1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 :


"June", 7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November",12 :
"December" }

2. Updating an element
 The values in dictionary can be modified.
 New key_value pairs can be inserted or deleted from the dictionary.
Syntax:
Dictionary_name[new_Key_value]=value

Eg:
months = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June", 7 :
"July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

print(“Before updating”,months)
months[1] = "Jan" # Updating an element
print (“After Updating”,months)

Output:
Before updating: { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May",6
: "June", 7 : “July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

After Updating: { 1 : "Jan", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June


",7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

3. Deleting an element:
Deletion can be done using following methods.
1.del
2.pop()
3.popitem()

1.del:
It is used to delete the elements in the dictionary.
Syntax:
Del dict_name[key]
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

del months[3] # deleting using del.


print(months)
Output:

{ 1 : "January", 2 : "February", 4 : "April", 5 : "May", 6 : "June", 7 : "July", 8 :”August",9 :


"September", 10 : "October", 11 : "November"}

2.popitem():
It is used to delete the elements in the dictionary using the key and value.
Syntax:
Dict_name.popitem(key:value)
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

months.popitem(11:”November”) # deleting using popitem.


print(months)
Output:
{ 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June", 7 : "July",
8 : "August",9 : "September", 10 : "October"}

3.pop():
It is used to delete the elements in the dictionary using the key.
Syntax:
Dict_name.popitem(key)
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

months.popitem(11) # deleting using popitem.


print(months)

Output:
{ 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",7 : "July",
8 : "August",9 : "September", 10 : "October"}

4.clear()
It deletes all the elements in the dictionary.
Syntax:
Dict_name.clear()
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}

months.clear() # deletes all items.


print(months)

Output:
{}

5.Sorting:
Sorts the elements in the dictionary in alphabetic order.
Eg:
months = { 1 : "January", 10 : "October", 2 : "February", 3: "March", 4 : "April", 5 :”May",
6 : "June", 9 : "September", 11 : "November” ,7 : "July", 8 : "August"}

sortedkeys = months.keys()
print (sortedkeys)

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Iterating over keys


months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : “June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 :”November",12:”December”}

for key in months:


print key, months[key]

Output:
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December

Iterating over (key, value) pairs


months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 :”November",12:”December”}

for key, value in months.iteritems():


print key, value
print "The entries in the dictionary are:"
for item in months.keys():
print "months[ ", item, " ] = ", months[ item ]

Combining List and Dictionary


customers = [{"uid":1,"name":"John"},
{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},] ]
print customers
Output:
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name':'Andersson'}]

Advanced List processing:

It is mainly carried out in two dimentional list.

The 2D list are used to solve data in the table or matrix.

Creating 2D list or Matrix:

Matrix1=[[list1 value].[list2 value]….[listn value]]

Eg:

matrix1=[[1,2,3],[4,5,6],[7,8,9]]

print(“matrix[0]=”,matrix1[0])

print(“matrix[1]=”,matrix1[1])

print(“matrix[2]=”,matrix1[2])

Output:

matrix[0]=[1,2,3]
matrix[1]=[4,5,6]

matrix[2]=[7,8,9]

Histogram:

It represents an accurate graphical representation of distribution of numerical data.

It is a diagram consists of bars.

Eg:
a = (0, 1, 1, 1, 2, 3, 7, 7, 23)
def count_elements(seq) -> dict:
"""Tally elements from `seq`."""
hist = {}
for i in seq:
hist[i] = hist.get(i, 0) + 1
return hist
counted = count_elements(a)

Output:
counted
{0: 1, 1: 3, 2: 1, 3: 1, 7: 2, 23: 1}

Functin to create histogram with “=” symbol

def histogram( items ):

for n in items:

output = ''

times = n

while( times > 0 ):

output += '='

times = times – 1

print(output)h

histogram([2, 3, 6, 5])

Output:
==
===
======
=====
List comprehensions
 It provide a concise way to create lists.
 It consists of brackets containing an expression followed by a for clause, thenzero or more
for or if clauses.
 The expressions can be anything, meaning you can put in all kinds of objects in lists.
 The result will be a new list resulting from evaluating the expression in the
context of the for and if clauses which follow it.
 The list comprehension always returns a result list.

Syntax:
The list comprehension starts with a '[' and ']', to help you remember that the
result is going to be a list.
[ expression for item in list if conditional ]

Eg:
x = [i for i in range(10)]
print x

Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Illustrative programs:

(i) Selection Sort:

Step 1: Define a function SelectionSort.


Step 2: Assign postionOfMax=0.
Step 2: Compare every location with postionOfMax.
Step 3: If location>positionOfMax, assign location to positionOfMax.
Step 4: Exchange the values fillslot and positionOfMax.
Step 6: Create a list.
Step 7: Print the list.
Step 8: Call the selectionSort and print the list.
Program:
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54,26,93,17,77,31,44,55,20]
print("Before Sort")
print(alist)
selectionSort(alist)
print("After sort")
print(alist)

Output:
Before sort:
[54,26,93,17,77,31,44,55,20]
After Sort:
[17,20,26,31,44,54,55,77,93]

(ii) Insertion Sort

Step1: Compare the current element in the iteration (say A) with the previous adjacent
element to it. If it is in order then continue the iteration else, go to step 2.
Step2: Swap the two elements (the current element in the iteration (A) and the previous
adjacent element to it).
Step3: Compare A with its new previous adjacent element. If they are not in order then
proceed to step 4.
Step4: Swap if they are not in order and repeat steps 3 and 4.
Step5: Continue the iteration.
Program:

a = [16, 19, 11, 15, 10, 12, 14]


#iterating over a
for i in a:
j = a.index(i)
#i is not the first element
while j>0:
#not in order
if a[j-1] > a[j]:
#swap
a[j-1],a[j] = a[j],a[j-1]
else:
#in order
break
j = j-1
print (a)
Output:
[10, 11, 12, 14, 15, 16, 19]

(iii)Merge sort:
 Merge sort is very different than the other sorting techniques we have seen so
far.
 Merge Sort can be used to sort an unsorted list or to merge two sorted lists.

Sort an unsorted list


The idea is to split the unsorted list into smaller groups until there is only one
element in a group. Then, group two elements in the sorted order and gradually
build the size of the group. Every time the merging happens, the elements in th e
groups must be compared one by one and combined into a single list in the sorted
order. This process continues till all the elements are merged and sorted. Note that
when the regrouping happens the sorted order must always be maintained.

Program:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
#recursion
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

Output:
('Splitting ', [54, 26, 93, 17, 77, 31, 44, 55, 20])
('Splitting ', [54, 26, 93, 17])
('Splitting ', [54, 26])
('Splitting ', [54])
('Merging ', [54])
('Splitting ', [26])
('Merging ', [26])
('Merging ', [26, 54])
('Splitting ', [93, 17])
('Splitting ', [93])
('Merging ', [93])
('Splitting ', [17])
('Merging ', [17])
('Merging ', [17, 93])
('Merging ', [17, 26, 54, 93])
('Splitting ', [77, 31, 44, 55, 20])
('Splitting ', [77, 31])
('Splitting ', [77])
('Merging ', [77])
('Splitting ', [31])
('Merging ', [31])
('Merging ', [31, 77])
('Splitting ', [44, 55, 20])
('Splitting ', [44])
('Merging ', [44])
('Splitting ', [55, 20])
('Splitting ', [55])
('Merging ', [55])
('Splitting ', [20])
('Merging ', [20])
('Merging ', [20, 55])
('Merging ', [20, 44, 55])
('Merging ', [20, 31, 44, 55, 77])
('Merging ', [17, 20, 26, 31, 44, 54, 55, 77, 93])
[17, 20, 26, 31, 44, 54, 55, 77, 93]

(iv) Quick Sort:


Step1: Create a function quicksort that takes a list and two variables start and end as
arguments.
Step2: If end – start is not greater than 1, return.
Step3: Find the index of the pivot, p by calling the function partition with the list and
variables start and end as arguments.
Step4: Call quicksort with the list and the variables start and p as arguments to sort the list
from start to p – 1.
Step5: Call quicksort with the list, the expression p + 1 and end as arguments to sort the list
from p + 1 to end – 1.
Step6: Define the function partition that takes a list and two variables start and end as
arguments.
Step7: The function parititon uses Hoare’s partition scheme to partition the list.
Program:
def quicksort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
p = partition(alist, start, end)
quicksort(alist, start, p)
quicksort(alist, p + 1, end)

def partition(alist, start, end):


pivot = alist[start]
i = start + 1
j = end - 1
while True:
while (i <= j and alist[i] <= pivot):
i=i+1
while (i <= j and alist[j] >= pivot):
j=j-1
if i <= j:
alist[i], alist[j] = alist[j], alist[i]
else:
alist[start], alist[j] = alist[j], alist[start]
return j
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
quicksort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)

You might also like