Python Chapter-2 (1)
Python Chapter-2 (1)
PIET
CSE Dept.
CHAPTER-2
Python Data Structure
What is Data Structure?
➢ Data structure identifies how data or values are stored in memory
W o r l d
0 1 2 3 4
String Library
➢ List of common function provided by string library
➢ Explore more using : dir(string_object)
• capitalize • join
• center • ljust
• count • Lower
• endswith • Lstrip
• find • replace
• Index • rjust
• Isalnum • rsplit
• Isalpha • Rstrip
• Isdigit • Startswith
• Islower • Swapcase
• isupper • upper
List
list_of_number = [ 1, 2.3, 3, 4, 0]
nita 12 pavan 13 14
0 1 2 3 4
List Methods
Methods Description
OR
Keys as Index
12 75 3
money tissues candy
Dictionary Methods
➢ get()
• give the value at given key if
key is there, otherwise create
given and assign default value
Example:
Output:
Stack and Queue
Hash tables are a type of data structure in which the address or the
index value of the data element is generated from a hash function.
Hash table stores key-value pairs but the key is generated through a
hashing function.
• The keys of the dictionary are hashable i.e. the are generated by
hashing function which generates unique result for each unique value
supplied to the hash function.
• The order of data elements in a dictionary is not fixed.
If we want to know the position of x in a list, the index method can be used.
>>> nums=[3,1,4,2,5]
>>>nums.index(4)
>>>2
Searching Algorithms
Linear Search:
search through the list of items one by one until the target value is found.
If the data is sorted, there is an even better searching strategy – one you
probably already know!
Binary means two, and at each step we are diving the remaining group of
numbers into two parts.
The heart of the algorithm is a loop that looks at the middle element of the
range, comparing it to the value x.
If x is smaller than the middle item, high is moved so that the search is
confined to the lower half.
If x is larger than the middle item, low is moved to narrow the search to the
upper half.
Searching Algorithms
Sorting in Python
Bubble Sort
It is a comparison-based algorithm in which each pair of adjacent elements is
compared and the elements are swapped if they are not in order.
Sorting in Python
Insertion Sort
Insertion sort involves finding the right place for a given element in a sorted list.
So in beginning we compare the first two elements and sort them by comparing
them.
Then we pick the third element and find its proper position among the previous
two sorted elements.
This way we gradually go on adding more elements to the already sorted list
by putting them in their proper position.
Sorting in Python
www.paruluniversity.ac.in