Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

Python 2024 Lecture Final

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

Python 2024 Lecture Final

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

UNIT – II

DATA STRUCTURES:

Data Structures in Python provides / include Python list, Python Tuple, Python set, and
Python dictionaries with their syntax and examples.

Here in this data structure we will come to know as a way of organizing and storing
data such that we can access and modify it efficiently

List:

 It is a general purpose most widely used in data structures


 List is a collection which is ordered and changeable and allows duplicate
members. (Grow and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and
separate values with commas.
 We can construct / create list in
many ways. Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

>>> x=list()
>>> x
[]

>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
The list data type has some more methods. Here are all of the methods of list objects:
List Operations:
 Del()
 Append()
 Extend()
 Insert()
 Pop()
 Remove()
 Reverse()
 Sort()
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]

>>> del(x)
>>> x # complete list gets deleted
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:

>>> x=[1,2,4,6,7]
>>> x.insert(2,10) #insert(index no, item to be inserted)

>>> x

[1, 2, 10, 4, 6, 7]

>>> x.insert(4,['a',11])

>>> x

[1, 2, 10, 4, ['a', 11], 6, 7]

Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.

>>> x=[1, 2, 10, 4, 6, 7]

>>> x.pop()

>>> x

[1, 2, 10, 4, 6]

>>> x=[1, 2, 10, 4, 6]

>>> x.pop(2)

10

>>> x

[1, 2, 4, 6]

Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]

>>> x.remove(33)

>>> x

[1, 2, 10, 4, 6]

>>> x.remove(4)

>>> x

[1, 2, 10, 6]

Reverse: Reverse the order of a given list.


>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]

>>> x.sort()

>>> x

[1, 2, 3, 4, 5, 6, 7]

>>> x=[10,1,5,3,8,7]

>>> x.sort()

>>> x

[1, 3, 5, 7, 8, 10]

Slicing: Slice out substrings, sub lists, sub Tuples using index.

[Start: stop: steps]


 Slicing will start from index and will go up to stop in step of steps.
 Default value of start is 0,
 Stop is last index of list
 And for step default is 1
Example:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
List:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>>
print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5,
6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
[2, 4, 6, 8]
Tuple:
>>> list1=(11,12,13,14)
>>> list1[:2]
(11, 12)
To create a slice:
>>> print(slice(3))
slice(None, 3, None)
>>> print(slice(2))
slice(None, 2, None)
>>>
print(slice(1,6,4))
slice(1, 6, 4)
To get substring from a given string using slice object:
>>> pystr='python'
>>> x=slice(3)
>>> print(pystr[x])
Pyt
Using –ve index:
>>> pystr='python'
>>> x=slice(1,-3,1)
>>> print(pystr[x])
>>> yt
To get sublist and sub-tuple from a given list and tuple respectively:
>>> list1=['s','v','u','c','e']
>>> tup1=('c','o','l','l','e','g','e')
>>> x=slice(1,4,1)
>>> print(tup1[x])
('o', 'l', 'l')
>>>
print(list1[x]) ['v',
'u', 'c']
>>> x=slice(1,5,2)
>>>
print(list1[x]) ['v',
'c']
>>> A
print(tup1[x]) ('o',
'l')
>>> x=slice(-1,-4,-1) #negative index
>>>
print(list1[x]) ['e',
'c', 'u']
>>> x=slice(-1,-4,-1) #negative index
>>> print(tup1[x])
('e', 'g', 'e')
>>> print(list1[0:3]) #extending indexing
syntax ['s', 'v', 'u']
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written
with round brackets.
 Supports all operations for sequences.
 Immutable, but member objects may be mutable.
 If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
 Tuples are more efficient than list due to python’s implementation.
We can construct tuple in many
ways: X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4

Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
-
>>> x=()
>>> x
()
-
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)

>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)

Some of the operations of tuple are:


 Access tuple items
 Change tuple items
 Loop through a tuple
 Count()
 Index()
 Length()

Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples are
unchangeable.

>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same

Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa

Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>>
x.count(2) 4

Index (): Searches the tuple for a specified value and returns the position of where it
was found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>>
x.index(2) 1

(Or)

>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1

Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12

Set:
A set is a collection which is unordered and unindexed with no duplicate elements. In
Python sets are written with curly brackets.

 To create an empty set we use set()


 Curly braces ‘{}’ or the set() function can be used to create sets
We can construct tuple in many
ways: X=set()
X={3,5,6,8}
X=set(list1)

Example:
>>> x={1,3,5,6}
>>> x
{1, 3, 5, 6}

>>> x=set()
>>> x
set()
-
>>> list1=[4,6,"dd",7]
>>> x=set(list1)
>>> x
{4, 'dd', 6, 7}

 We cannot access items in a set by referring to an index, since sets are


unordered the items has no index.
 But you can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.

Some of the basic set operations are:


 Add()
 Remove()
 Len()
 Item in x
 Pop
 Clear

Add (): To add one item to a set use the add () method. To add more than one item to a
set use the update () method.

>>> x={"svcet","college","cie","dept"}
>>> x.add("autonomous")
>>> x
{'svcet', 'dept', 'autonomous', 'cie', 'college'}
-
>>> x={1,2,3}
>>> x.update("a","b")
>>> x
{1, 2, 3, 'a', 'b'}

-
>>> x={1,2,3}
>>> x.update([4,5],[6,7,8])
>>> x
{1, 2, 3, 4, 5, 6, 7, 8}
Remove (): To remove an item from the set we use remove or discard methods.
>>> x={1, 2, 3, 'a', 'b'}
>>> x.remove(3)
>>> x
{1, 2, 'a', 'b'}
Len (): To know the number of items present in a set, we use len().
>>> z={'svcet', 'dept', 'autonomous', 'cie', 'college'}
>>> len(z)
5

Item in X: you can loop through the set items using a for loop.
>>> x={'a','b','c','d'}
>>> for item in x:
print(item)

c
d
a
b

pop ():This method is used to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.

>>> x={1, 2, 3, 4, 5, 6, 7, 8}
>>> x.pop()
1
>>> x
{2, 3, 4, 5, 6, 7, 8}

Clear (): This method will the set as empty.


>>> x={2, 3, 4, 5, 6, 7, 8}
>>> x.clear()
>>> x
set()

The set also consist of some mathematical operations like:


Intersection AND &
Union OR |
Symmetric Diff XOR ^
Diff In set1 but not in set2 set1-set2
Subset set2 contains set1 set1<=set2
Superset set1 contains set2 set1>=set2
Some examples:

>>> x={1,2,3,4}
>>> y={4,5,6,7}
>>> print(x|y)
{1, 2, 3, 4, 5, 6, 7}

>>> x={1,2,3,4}
>>> y={4,5,6,7}
>>> print(x&y)
{4}
-
>>> A={1,2,3,4,5}
>>> B={4,5,6,7,8}
>>> print(A-B)
{1, 2, 3}

>>> B={4,5,6,7,8}
>>> A={1,2,3,4,5}
>>> print(B^A)
{1, 2, 3, 6, 7, 8}

Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
 Key-value pairs
 Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3)
(‘b’,4)]
X=dict(‘A’=1,’B’ =2)

Examples:
>>> dict1 = {"brand":"svcet","model":"college","year":1959}
>>> dict1
{'brand': 'svcet', 'model': 'college', 'year': 1959}

To access specific value of a dictionary, we must pass its key,


>>> dict1 = {"brand":"svcet","model":"college","year":1959}
>>> x=dict1["brand"]
>>> x
'svcet'
-
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"svcet","model":"college","year":1959}
>>> dict1.keys()
dict_keys(['brand', 'model',
'year'])
>>> dict1.values()
dict_values(['svcet', 'college', 1959])
>>> dict1.items()
dict_items([('brand', 'svcet'), ('model', 'college'), ('year', 1959)])
-
>>> for items in
dict1.values():
print(items)

svcet
college
1959

>>> for items in


dict1.keys():
print(items)

brand
mode
l year
>>> for i in
dict1.items():
print(i)

('brand', 'svcet')
('model', 'college')
('year', 1959)

Some of the operations are:


 Add/change
 Remove
 Length
 Delete

Add/change values: You can change the value of a specific item by referring to its key
name

>>> dict1 = {"brand":"svcet","model":"college","year":1959}


>>> dict1["year"]=2005
>>> dict1
{'brand': 'svcet', 'model': 'college', 'year': 2005}

Remove(): It removes or pop the specific item of dictionary.

>>> dict1 = {"brand":"svcet","model":"college","year":1959}


>>> print(dict1.pop("model"))
college
>>> dict1
{'brand': 'svcet', 'year': 2005}

Delete: Deletes a particular item.

>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}


>>> del x[5]
>>> x

Length: we use len() method to get the length of dictionary.

>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4
Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x:
print(key, x[key])

11
24
39
4 16
5 25
>>> for k,v in
x.items():
print(k,v)

11
24
39
4 16
5 25

List of Dictionaries:

>>> customers = [{"uid":1,"name":"John"},


{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},
]
>>> >>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'Andersson'}]

## Print the uid and name of each customer


>>> for x in customers:
print(x["uid"], x["name"])

1 John
2 Smith
3 Andersson

## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name':

'charlie'}] ## Add a new field to each entry

>>> for x in customers:


x["password"]="123456" # any initial value

>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password':
'123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]

## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
'123456'}]

>>> del customers[1]


>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}]

## Delete all fields

>>> for x in
customers: del
x["uid"]

>>> x
{'name': 'John', 'password': '123456'}

Sequences:
A sequence is a succession of values bound together by a container that reflects their
type. Almost every stream that you put in python is a sequence. Some of them are:

 String
 List
 Tuples
 Range object
String: A string is a group of characters. Since Python has no provision for arrays, we
simply use strings. This is how we declare a string. We can use a pair of single or double
quotes. Every string object is of the type ‘str’.

>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('svcet')
>>> a
'svcet'
>>> a=str(svcet)
>>> a[2]
'c'

List: A list is an ordered group of items. To declare it, we use square brackets.

>>> college=["cie","it","eee","ece","mech","aero"]
>>>
college[1] 'it'
>>>
college[:2]
['cie', 'it']
>>>
college[:3]
['cie', 'it', 'eee']
>>> college[3:]
['ece', 'mech',
'aero']
>>> college[0]="ciedept"
>>> college
['ciedept', 'it', 'eee', 'ece', 'mech', 'aero']

Tuple: It is an immutable group of items. When we say immutable, we mean we cannot


change a single value once we declare it.
>>> x=[1,2,3]
>>> y=tuple(x)
>>> y
(1, 2, 3)

>>> hello=tuple(["svcet","college"])
>>> hello
('svcet', 'college')

Range object: A range() object lends us a range to iterate on; it gives us a list of
numbers.

>>> a=range(4)
>>> type(a)
<class 'range'>

>>> for i in
range(1,6,2):
print(i)

1
3
5

Some of the python sequence operations and functions are:


1. Indexing
2. Slicing
3. Adding/Concatenation
4. Multiplying
5. Checking membership
6. Iterating
7. Len()
8. Min()
9. Max()
10.Sum()
11.Sorted(
)
12.Count()
13.Index()

1. Indexing
Access any item in the sequence using its index.
String List
>>> x='svcet' >>> x=['a','b','c']
>>> print(x[2]) >>> print(x[1])
c b

2. Slicing
Slice out substrings, sub lists, sub tuples using index
[start : stop : step size]

>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'

3. Adding/concatenation:
Combine 2 sequences of same type using +.
string List
>>> x='svcet' + 'college' >>> x=['a','b'] + ['c']
>>> print(x) >>> print(x)
Svcetcollege ['a', 'b', 'c']

4. Multiplying:
Multiply a sequence using *.

String List
>>> x='svcet'*3 >>> x=[3,4]*2
>>> x >>> x
'svcetsvcetsvcet' [3, 4, 3, 4]

5. Checking Membership:
Test whether an item is in or not in a sequence.

String List
>>> x='svcet' >>> x=['a','b','c']
>>> print('c' in x) >>> print('a' not in x)
True False

6. Iterating:
Iterate through the items in asequence

>>> x=[1,2,3]
>>> for item in x:
print(item*2)

2
4
6

If we want to display the items of a given list with index then we have to use
“enumerate” keyword.

>>> x=[5,6,7]
>>> for item,index in
enumerate(x):
print(item,index)

05
16
27

7. len():
It will count the number of items in a given sequence.

string List
>>> x="svcet" >>> x=["aa","b",'c','cc']
>>> print(len(x)) >>> print(len(x))
5 4

8. min():
Finds the minimum item in a given sequence lexicographically.

string List
>>> x="svcet" >>> x=["apple","ant1","ant"]
>>> print(min(x)) >>> print(min(x))
C ant

It is an alpha-numeric type but cannot mix types.

>>> x=["apple","ant1","ant",11]
>>> print(min(x))

Traceback (most recent call last):


File "<pyshell#73>", line 1, in <module>
print(min(x))
TypeError: '<' not supported between instances of 'int' and 'str'

9. max():
Finds the maximum item in a given sequence

string List
>>> x='cognizant' >>> x=["hello","yummy","zebra"]
>>> print(max(x)) >>>
Z print(max(x))
zebra

It is an alpha-numeric type but cannot mix types.

>>> x=["hello","yummy1","zebra1",22]
>>> print(max(x))

Traceback (most recent call last):


File "<pyshell#79>", line 1, in <module>
print(max(x))
TypeError: '>' not supported between instances of 'int' and 'str'

10. Sum:
Finds the sum of items in a sequence

>>> x=[1,2,3,4,5]
>>>
print(sum(x)) 15

>>> print(sum(x[-
2:])) 9

Entire string must be numeric type.


>>> x=[1,2,3,4,5,"svcet"]
>>> print(sum(x))

Traceback (most recent call last):


File "<pyshell#83>", line 1, in <module>
print(sum(x))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

11.Sorted():
Returns a new list of items in sorted order but does not change the original list.

string List
>>> x='college' >>> x=['a','r','g','c','j','z']
>>> print(sorted(x)) >>> print(sorted(x))
['c', 'e', 'e', 'g', 'l', 'l', 'o'] ['a', 'c', 'g', 'j', 'r', 'z']

12.Count():
It returns the count of an item

string List
>>> x='college' >>> x=['a','b','a','a','c','a']
>>> print(x.count('l')) >>> print(x.count('a'))
2 4
>>> 'college'.count('l')
2
13.Index()
Returns the index of first occurrence

string List
>>> x='college' >>> x=['a','b','a','a','c','a']
>>> >>> print(x.index('a'))
print(x.index('l')) 2 0

Comprehensions:
List:

List comprehensions provide a concise way to create lists. Common applications are to make
new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a
certain condition.

For example, assume we want to create a list of squares, like:

>>> list1=[]

>>> for x in range(10):

list1.append(x**2)

>>> list1

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

(or)

This is also equivalent to

>>> list1=list(map(lambda x:x**2, range(10)))

>>> list1

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

(or)
Which is more concise and redable.

>>> list1=[x**2 for x in range(10)]

>>> list1

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Similarily some examples:

>>> x=[m for m in range(8)]


>>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7]

>>> x=[z**2 for z in range(10) if z>4]


>>> print(x)
[25, 36, 49, 64, 81]

>>> x=[x ** 2 for x in range (1, 11) if x % 2 == 1]


>>> print(x)
[1, 9, 25, 49, 81]

>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)

[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]
Tuple:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator"
object that we can iterate over.

For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>

>>> print(x)
<generator object <genexpr> at 0x033EEC30>

You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE. So, given the code

>>> x = (i for i in 'abc')


>>> for i in x:
print(i)

a
b
c
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

Set:
Similarly to list comprehensions, set comprehensions are also supported:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}


>>> a
{'r', 'd'}
>>> x={3*x for x in range(10) if x>5}
>>> x
{24, 18, 27, 21}

Dictionary:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions:

>>> z={x: x**2 for x in (2,4,6)}


>>> z
{2: 4, 4: 16, 6: 36}

>>> dict11 = {x: x*x for x in range(6)}


>>> dict11
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
UNIT – V
Sorting:

Bubble Sort:

It is a simple sorting algorithm which sorts ‘n’ number of elements in the list by
comparing the ach pair of adjacent items and swaps them if they are in wrong order.

Algorithm:

1. Starting with the first element (index=0), compare the current element with the
next element of a list.
2. If the current element is greater (>) than the next element of the list then swap them.
3. If the current element is less (<) than the next element of the list move to the next
element.
4. Repeat step 1 until it correct order is framed.

For ex: list1= [10, 15, 4, 23, 0] so here we are comparing values again

If > --- yes ---- swap and again, so we use

loops. If < --- No Do nothing/remains same

#Write a python program to arrange the elements in ascending order using


bubble sort:
list1=[9,16,6,26,0]
print("unsorted list1 is",
list1) for j in
range(len(list1)-1):
for i in range(len(list1)-
1): if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)

Output:
unsorted list1 is [9, 16, 6, 26, 0]
[9, 16, 6, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 0, 26]

[6, 9, 16, 0, 26]


[6, 9, 16, 0, 26]
[6, 9, 0, 16, 26]
[6, 9, 0, 16, 26]

[6, 9, 0, 16, 26]


[6, 0, 9, 16, 26]
[6, 0, 9, 16, 26]
[6, 0, 9, 16, 26]

[0, 6, 9, 16, 26]


[0, 6, 9, 16, 26]
[0, 6, 9, 16, 26]
[0, 6, 9, 16, 26]

sorted list is [0, 6, 9, 16, 26]

#If we want to reduce no of iterations/steps in output:


C:/Users/SVCET/AppData/Local/Programs/Python/Python38-
32/pyyy/bubb.py list1=[9,16,6,26,0]
print("unsorted list1 is", list1)
for j in range(len(list1)-1,0,-
1): for i in range(j):
if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)
Output:

C:/Users/SVCET/AppData/Local/Programs/Python/Python38-
32/pyyy/bubb2.py unsorted list1 is [9, 16, 6, 26, 0]
[9, 16, 6, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 0, 26]

[6, 9, 16, 0, 26]


[6, 9, 16, 0, 26]
[6, 9, 0, 16, 26]

[6, 9, 0, 16, 26]


[6, 0, 9, 16, 26]

[0, 6, 9, 16, 26]

sorted list is [0, 6, 9, 16, 26]

# In a different way:

list1=[9,16,6,26,0]
print("unsorted list1 is", list1)
for j in range(len(list1)-1):
for i in range(len(list1)-1-j):
if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)
Output:

C:/Users/SVCET/AppData/Local/Programs/Python/Python38-32/pyyy/bubb3.py

unsorted list1 is [9, 16, 6, 26, 0]


[9, 16, 6, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 0, 26]

[6, 9, 16, 0, 26]


[6, 9, 16, 0, 26]
[6, 9, 0, 16, 26]

[6, 9, 0, 16, 26]


[6, 0, 9, 16, 26]

[0, 6, 9, 16, 26]

sorted list is [0, 6, 9, 16, 26]

# Program to give input from the user to sort the elements


list1=[]
num=int(input("enter how many
numbers:")) print("enter values")
for k in range(num):
list1.append(int(input()))
print("unsorted list1 is",
list1) for j in
range(len(list1)-1):
for i in range(len(list1)-
1): if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)

Output:
C:/Users/SVCET/AppData/Local/Programs/Python/Python38-32/pyyy/bubb4.py

enter how many


numbers:5 enter values
5
77
4
66
30
unsorted list1 is [5, 77, 4, 66, 30]
[5, 77, 4, 66, 30]
[5, 4, 77, 66, 30]
[5, 4, 66, 77, 30]
[5, 4, 66, 30, 77]

[4, 5, 66, 30, 77]


[4, 5, 66, 30, 77]
[4, 5, 30, 66, 77]
[4, 5, 30, 66, 77]

[4, 5, 30, 66, 77]


[4, 5, 30, 66, 77]
[4, 5, 30, 66, 77]
[4, 5, 30, 66, 77]

[4, 5, 30, 66, 77]


[4, 5, 30, 66, 77]
[4, 5, 30, 66, 77]
[4, 5, 30, 66, 77]

sorted list is [4, 5, 30, 66, 77]

#bubble sort program for descending order

list1=[9,16,6,26,0]
print("unsorted list1 is",
list1) for j in
range(len(list1)-1):
for i in range(len(list1)-
1): if list1[i]<list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)

Output:
C:/Users/SVCET/AppData/Local/Programs/Python/Python38-
2/pyyy/bubbdesc.py unsorted list1 is [9, 16, 6, 26, 0]
[16, 9, 6, 26, 0]
[16, 9, 6, 26, 0]
[16, 9, 26, 6, 0]
[16, 9, 26, 6, 0]

[16, 9, 26, 6, 0]
[16, 26, 9, 6, 0]
[16, 26, 9, 6, 0]
[16, 26, 9, 6, 0]

[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]

[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]

sorted list is [26, 16, 9, 6, 0]

Selection Sort:

Sort (): Built-in list method


Sorted (): built in function
 Generally this algorithm is called as in-place comparison based algorithm.
We compare numbers and place them in correct position.
 Search the list and find out the min value, this we can do it by min () method.
 We can take min value as the first element of the list and compare with the
next element until we find small value.
Algorithm:
1. Starting from the first element search for smallest/biggest element in the list
of numbers.
2. Swap min/max number with first element
3. Take the sub-list (ignore sorted part) and repeat step 1 and 2 until all the
elements are sorted.
#Write a python program to arrange the elements in ascending order using selection
sort:
list1=[5,3,7,1,9,6]
print(list1)
for i in range(len(list1)):
min_val=min(list1[i:])
min_ind=list1.index(min_val)
list1[i],list1[min_ind]=list1[min_ind],list1[i]
print(list1)

Output:
C:/Users/SVCET/AppData/Local/Programs/Python/Python38-32/pyyy/selectasce.py

[5, 3, 7, 1, 9, 6]
[1, 3, 7, 5, 9, 6]
[1, 3, 7, 5, 9, 6]
[1, 3, 5, 7, 9, 6]
[1, 3, 5, 6, 9, 7]
[1, 3, 5, 6, 7, 9]
[1, 3, 5, 6, 7, 9]
#Write a python program to arrange the elements in descending order using selection
sort:
list1=[5,3,7,1,9,6]

print(list1)

for i in range(len(list1)):

min_val=max(list1[i:])

min_ind=list1.index(min_val)

list1[i],list1[min_ind]=list1[min_ind],list1[i]
print(list1)

Output:
C:/Users/SVCET/AppData/Local/Programs/Python/Python38-32/pyyy/selecdecs.py

[5, 3, 7, 1, 9, 6]

[9, 7, 6, 5, 3, 1]

Note: If we want the elements to be sorted in descending order use max () method in place
of min ().

Insertion Sort:

 Insertion sort is not a fast sorting algorithm. It is useful only for small datasets.
 It is a simple sorting algorithm that builds the final sorted list one item at a time.

Algorithm:

1. Consider the first element to be sorted & the rest to be unsorted.


2. Take the first element in unsorted order (u1) and compare it with sorted
part elements(s1)
3. If u1<s1 then insert u1 in the correct order, else leave as it is.
4. Take the next element in the unsorted part and compare with sorted element.
5. Repeat step 3 and step 4 until all the elements get sorted.

# Write a python program to arrange the elements in ascending order using insertion
sort (with functions)
def insertionsort(my_list):

#we need to sorrt the unsorted part at a

time. for index in range(1,len(my_list)):

current_element=my_list[index]

pos=index

while current_element<my_list[pos-1]and

pos>0: my_list[pos]=my_list[pos-1]

pos=pos-1

my_list[pos]=current_element
list1=[3,5,1,0,10,2] num=int(input(“enter how many elements to be in
list”)) insertionsort(list1) list1=[int(input()) for i in range (num)]
print(list1)

Output:

C:/Users/SVCET/AppData/Local/Programs/Python/Python38-
32/pyyy/inserti.py [0, 1, 2, 3, 5, 10]

# Write a python program to arrange the elements in descending order using insertion
sort (with functions)
def insertionsort(my_list):

#we need to sorrt the unsorted part at a

time. for index in range(1,len(my_list)):

current_element=my_list[index]

pos=index

while current_element>my_list[pos-1]and

pos>0: my_list[pos]=my_list[pos-1]

pos=pos-1

my_list[pos]=current_element

#list1=[3,5,1,0,10,2]

#insertionsort(list1)

#print(list1)

num=int(input("enter how many elements to be in

list")) list1=[int(input())for i in range(num)]

insertionsort(list1)

print(list1)
Output:

C:/Users/SVCET/AppData/Local/Programs/Python/Python38-32/pyyy/insertdesc.py
enter how many elements to be in list 5
8
1
4
10
2
[10, 8, 4, 2, 1]
Merge Sort:

Generally this merge sort works on the basis of divide and conquer algorithm. The three
steps need to be followed is divide, conquer and combine. We will be dividing the unsorted
list into sub list until the single element in a list is found.

Algorithm:

1. Split the unsorted list.


2. Compare each of the elements and group them
3. Repeat step 2 until whole list is merged and sorted.

# Write a python program to arrange the elements in ascending order using Merge
sort (with functions)
def
mergesort(list1):
if len(list1)>1:
mid=len(list1)//2
left_list=list1[:mid]
right_list=list1[mid:]
mergesort(left_list)
mergesort(right_list)
i=0
j=0
k=0
while i<len(left_list) and j<len(right_list):
if left_list[i]<right_list[j]:
list1[k]=left_list[i]
i=i+1
k=k+1
else:
list1[k]=right_list[j]
j=j+1
k=k+1
while
i<len(left_list):
list1[k]=left_list[i
] i=i+1
k=k+1
while
j<len(right_list):
list1[k]=right_list[j
] j=j+1
k=k+1
num=int(input("how many numbers in
list1")) list1=[int(input()) for x in
range(num)] mergesort(list1)
print("sorted list1",list1)

Output:
C:/Users/SVCET/AppData/Local/Programs/Python/Python38-32/pyyy/merg.py
how many numbers in
list15 5
9
10
1
66
sorted list1 [1, 5, 9, 10, 66]

Quick Sort:

Algorithm:
1. Select the pivot element
2. Find out the correct position of pivot element in the list by rearranging it.
3. Divide the list based on pivot element
4. Sort the sub list recursively

Note: Pivot element can be first, last, random elements or median of three values.

In the following program we are going to write 3 functions. The first function is to find pivot
element and its correct position. In second function we divide the list based on pivot element
and sort the sub list and third function (main fun) is to print input and output.
# Write a python program to arrange the elements in ascending order using Quick sort
(with functions)
#To get the correct position of pivot element:
def
pivot_place(list1,first,last):
pivot=list1[first]
left=first+1
right=last
while True:
while left<=right and list1[left]<=pivot:
left=left+1
while left<=right and
list1[right]>=pivot: right=right-1
if right<left:
break
else:
list1[left],list1[right]=list1[right],list1[left]
list1[first],list1[right]=list1[right],list1[first]
return right
#second function
def
quicksort(list1,first,last):
if first<last:
p=pivot_place(list1,first,last)
quicksort(list1,first,p-1)
quicksort(list1,p+1,last)
#main fun
list1=[56,25,93,15,31,44]
n=len(list1)
quicksort(list1,0,n-1)
print(list1)

Output:
C:/Users/SVCET/AppData/Local/Programs/Python/Python38-32/pyyy/qucksort.py
[15, 25, 31, 44, 56, 93]

# Write a python program to arrange the elements in descending order using Quick
sort (with functions)
#To get the correct position of pivot element:
def pivot_place(list1,first,last):
pivot=list1[first]
left=first+1
right=last
while
True:
while left<=right and list1[left]>=pivot:
left=left+1
while left<=right and
list1[right]<=pivot: right=right-1
if right<left:
break
else:
list1[left],list1[right]=list1[right],list1[left]
list1[first],list1[right]=list1[right],list1[first]
return right
def
quicksort(list1,first,last):
if first<last:
p=pivot_place(list1,first,last)
quicksort(list1,first,p-1)
quicksort(list1,p+1,last)
#main fun
list1=[56,25,93,15,31,44]
n=len(list1)
quicksort(list1,0,n-1)
print(list1)

Output:

C:/Users/SVCET/AppData/Local/Programs/Python/Python38-

32/pyyy/qukdesc.py [93, 56, 44, 31, 25, 15]

Linked Lists:

Linked lists are one of the most commonly used data structures in any programming
language. Linked Lists, on the other hand, are different. Linked lists, do not store data at
contiguous memory locations. For each item in the memory location, linked list stores value
of the item and the reference or pointer to the next item. One pair of the linked list item and
the reference to next item constitutes a node.
The following are different types of linked lists.

 Single Linked List


A single linked list is the simplest of all the variants of linked lists. Every node in a
single linked list contains an item and reference to the next item and that's it.

 Doubly Linked List


 Circular Linked List
 Linked List with Header
 Sorted Linked List

# Python program to create a linked list and display its elements.


The program creates a linked list using data items input from the user and displays it.
Solution:

1. Create a class Node with instance variables data and next.


2. Create a class Linked List with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points
to the last.
4. Define methods append and display inside the class Linked List to append
data and display the linked list respectively.
5. Create an instance of Linked List, append data to it and display the list.
Program:
class Node:
def init (self, data):
self.data = data
self.next = None

class LinkedList:
def init (self):
self.head = None
self.last_node =
None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next

a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()

Program Explanation

1. An instance of Linked List is created.


2. The user is asked for the number of elements they would like to add. This is stored in n.
3. Using a loop, data from the user is appended to the linked list n times.
4. The linked list is displayed.
Output:
C:/Users/SVCET/AppData/Local/Programs/Python/Python38-
32/pyyy/link1.py How many elements would you like to add? 5 Enter data
item:
4 Enter data
item: 4 Enter
data item: 6
Enter data item:
8 Enter data
item: 9
The linked list: 4 4 6 8 9

Stacks:
Stack works on the principle of “Last-in, first-out”. Also, the inbuilt functions in Python
make the code short and simple. To add an item to the top of the list, i.e., to push an item,
we use append() function and to pop out an element we use pop() function.
# Python code to demonstrate Implementing stack using list

stack = ["Amar", "Akbar",


"Anthony"] stack.append("Ram")
stack.append("Iqbal")
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)

Output:
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Iqbal
['Amar', 'Akbar', 'Anthony', 'Ram']
Ram
['Amar', 'Akbar', 'Anthony']
Queues:

Queue works on the principle of “First-in, first-out”. Time plays an important factor here.
We saw that during the implementation of stack we used append() and pop() function which
was efficient and fast because we inserted and popped elements from the end of the list, but
in queue when insertion and pops are made from the beginning of the list, it is slow. This
occurs due to the properties of list, which is fast at the end operations but slow at the
beginning operations, as all other elements have to be shifted one by one. So, we prefer the
use of collections. Deque over list, which was specially designed to have fast appends and
pops from both the front and back end.

#Python code to demonstrate Implementing Queue using deque and list


from collections import deque
queue = deque(["Ram", "Tarun", "Asif",
"John"]) print(queue)
queue.append("Akbar")
print(queue)
queue.append("Birbal")
print(queue)
print(queue.popleft())
print(queue.popleft())
print(queue)

Output:
deque(['Ram', 'Tarun', 'Asif', 'John'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])
Ram
Tarun
deque(['Asif', 'John', 'Akbar', 'Birbal'])

You might also like