datastructures in python

45
Datastructures in Python - Ram Sagar Mourya Hyderabad Python User Group

Upload: hydpy

Post on 13-Jan-2017

54 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Datastructures in python

Datastructures in Python

- Ram Sagar Mourya

Hyderabad Python User Group

Page 2: Datastructures in python

Types of data structuresThere two types of data structures:• Built-in data structures, data structures that

provided by default Eg: list, dictionary ,tuple…

• User-defined data structures (classes in object oriented programming) that are designed for a particular task

Eg: Stack , Queue…

Page 3: Datastructures in python

Python built in data structures• Python has set of built in data structures :

– lists– tuples– dictionaries– sets

Page 4: Datastructures in python

Lists• An ordered collection of items

• List items does not need to be of same typeWe can have numbers, strings , list etc in the same list

• List notation• A = [1,”This is a list”, ‘c’,2.5] • B = []• C = list()

Page 5: Datastructures in python

Create a List

Page 6: Datastructures in python

• Make a list using string

>>> lst = 'Welcome to meetup'.split()>>> lst['Welcome', 'to', 'meetup']

>>> lst = 'What,a,wonderful,world'.split(',')>>> lst['What', 'a', 'wonderful', 'world']

Page 7: Datastructures in python

• Access the items in the list

>> names = [ ‘Rahul’, ‘Mahesh, ‘Aishwarya’ ]

• Read one : >> names[0]

>> Rahul

>> names[-1] >> Aishwarya

• Read one at a time : >> for name in names:

print name Rahul

Mahesh Aishwarya

Page 8: Datastructures in python

Methods of Lists• List.append(x)

– Adds an item to the end of the listEg: >> list_items = [1, 2, 3, 4, 5]>> list_items.append(6)>> list_items>> [ 1, 2, 3, 4, 5, 6 ]

Page 9: Datastructures in python

• List.extend(L)- Extends the list by appending all the items in the given list ‘L’ to the existing list

Eg: >> list_items = [1, 2, 3, 4, 5]>> list_items.extend([6, 7, 8, 9])>> list_items>> [ 1, 2, 3, 4, 5, 6, 7, 8 , 9 ]

Page 10: Datastructures in python

• List.insert(i,x)- Inserts an item x at index i

Eg: >> list_items = [1, 2, 3, 4, 5]>> list_items.insert(3, 10)>> list_items>> [ 1, 2, 3, 10, 4, 5]

Page 11: Datastructures in python

• List.remove(x)- Removes the first occurrence of the item from the list

whose value is xEg: >> list_items = [1, 5, 3, 4, 5, 5]>> list_items.remove(5)>> list_items>> [ 1, 3, 4, 5, 5]

Page 12: Datastructures in python

• List.pop(i) - Remove and returns item at index i,default value of i is last index of the listEg: >> list_items = [1, 5, 3, 4, 5, 8]>> list_items.pop()>> 8>> lst>> [1, 5, 3, 4, 5]

>> list_items.pop(2)>> 3>> lst[1, 5, 4, 5]

Page 13: Datastructures in python

Some other methods of Lists• >> a = [1, 2, 3, 4, 5, 6, 7, 6]

• a.count(x) # Returns occurrence of specified x>> a.count(6)>> 2

• a.index(x) # Returns the first index where the given value appears >> a.index(6)

>> 5• a.reverse() # Reverses order of list

>> a.reverse()>> [6, 7, 6, 5, 4, 3, 2, 1]

• a.sort() >> a>> [1, 2, 3, 4, 5, 6, 6, 7]

Page 14: Datastructures in python

Slicing a List• List[ start, stop]

>> lst = list(‘Monty Python’)>> lst>> ['M', 'o', 'n', 't', 'y', ' ', 'P', 'y', 't', 'h', 'o', 'n']

>> lst[6:10]>> ['P', 'y', 't', 'h']

>> lst[0 : 5]>> ['M', 'o', 'n', 't', 'y']

Page 15: Datastructures in python

>> lst[6: 10]>> [''P', 'y', 't', 'h', 'o']

>> lst[-12 : -7]>> ['M', 'o', 'n', 't', 'y']

>> lst[:5]>> ['M', 'o', 'n', 't', 'y']

>> lst[5:]>> [' ', 'P', 'y', 't', 'h', 'o', 'n']

Page 16: Datastructures in python

Practice1). Write a program to read the input and process it Input will be items separated by space. Perform the following actions. a). Make a list of the input provided and print it b). Count the no of items in the list and print it c). Ask the user to provide a item as input and find the index of the item , if the item is not present print ‘Item not found’ else print the index. Find the Occurrence of the item in the list d). Reverse the list and print it e). Sort the list in descending order and print the sorted list

Input :Enter the numbers :a c d e z k m o

Page 17: Datastructures in python

Practice

Page 18: Datastructures in python

Dictionary

• Consists of Key– Value pair• Keys needs to unique• Items of the dictionary are not ordered

Eg:>> empty_dict = dict() >> empty_dict >> {}

>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> phonebook>> {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}

>> Phonebook['Rock‘]>> 999999999

Page 19: Datastructures in python

Modifying a Dictionary>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> phonebook['Rock‘] = 666666666>> phonebook>> {'Rock': 666666666, 'Rashmi': 888888888, 'Mohan': 777777777}

>> phonebook['Ricky'] = 3333333333>> phonebook>> {'Rock': 999999999, 'Ricky': 3333333333, 'Rashmi': 888888888, 'Mohan': 777777777}

Page 20: Datastructures in python

Methods in Dictionarydict.keys()>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> phonebook.keys()>> ['Mohan', 'Rashmi', 'Rock']

dict.values()>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> phonebook.values()>> [777777777, 888888888, 999999999]

Page 21: Datastructures in python

• dict.items()

>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> phonebook.items()>> [('Mohan', 777777777), ('Rashmi', 888888888), ('Rock', 999999999)]

Page 22: Datastructures in python

dict.clear()

>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> phonebook.clear()>> phonebook>> {}

Page 23: Datastructures in python

dict.copy()>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> newPhoneBook = phonebook.copy()>> newPhoneBook >>{'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}

Page 24: Datastructures in python

• dict.get(key)

>> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> phonebook['Akshay']>> phonebook.get('Mohan')

Page 25: Datastructures in python

• in keyword :

> >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}>> ‘Akshay’ in phonebook>> False>> ‘Rock’ in phonebook>> True

Page 26: Datastructures in python

PracticeWrite a program to read the student and marks and make a dictionary Sample Input: Enter the details : Mahesh 20 Output: {‘Mahesh’ : 20 }

Page 27: Datastructures in python

Practice2. Write a program to read the names from the user and make a list of names , then loop through the list of name and ask for email. Make a dictionary of name,emailSample Input :

Output:

Page 28: Datastructures in python

Tuples

• A tuple is a sequence of immutable Python objects. • Tuples are sequences, just like lists. • Any constant data that won’t change , better to use tuple

>> tup1 = ()

>> tup2 = ('physics', 'chemistry', 1997, 2000)>> tup3 = (1, 2, 3, 4, 5 )>> tup4 = "a", "b", "c", "d"

Page 29: Datastructures in python

Accessing items in Tuple• Item can be access using the index

>> languages = ('Hindi','English','Telugu','Gujarati','Marathi')>> languages[0]>> 'Hindi'

• Slicing can be used in Tuple >> languages[0:3]('Hindi', 'English', 'Telugu')

Page 30: Datastructures in python

Simple example of Tuple• Swapping of numbers:>> a= 1>> b = 2>> temp = a>> a = b>> b = temp>> a2>> b1

>> a = 1>> b = 2>> a, b = b, a>> a2>> b1

Page 31: Datastructures in python

Set• Sets are unordered collections of simple objects• Unique collections of immutable objects

• Define a Set:

>> set1 = set()>> set2 = {'Ramesh','Mahes','Suresh'}

>> country = set(['India','America','Africa'])>> country>> set(['Africa', 'America', 'India', 'China'])

Page 32: Datastructures in python

Methods in Set• Set.add(element)

>> set2 = {'Ramesh','Mahes','Suresh'}>> set2.add('Himesh')>> set2>> set(['Himesh', 'Ramesh', 'Suresh', 'Mahes'])

Page 33: Datastructures in python

• copy

>> names = {'Ramesh','Mahesh','Suresh'}>> new_names = names.copy()>> new_names>> set(['Mahesh', 'Ramesh', 'Suresh'])

Page 34: Datastructures in python

• clear

>> names = {'Ramesh','Mahesh','Suresh'}>> names.clear()>> names>> set([])

Page 35: Datastructures in python

• difference

>> x = {"a","b","c","d","e"}>> y = {"b","c"} >> x.difference(y)>> set(['a', 'e', 'd'])

Page 36: Datastructures in python

• discard(ele)

>> x = {"a","b","c","d","e"}>> x.discard("b")>> x>> set(['a', ‘c', 'e', 'd'])

Page 37: Datastructures in python

• remove(ele)

>> x = {"a","b","c","d","e"}>> x.remove("b")>> x>> set(['a', ‘c', 'e', 'd'])

Page 38: Datastructures in python

• intersection

>> x = {"a","b","c"}>> y = {"d","e"}>> x.intersection(y)>> set([])>> y.add("b")>> x.intersection(y)>> set(["b"])

Page 39: Datastructures in python

• union

>> x = {"a","b","c"}>> y = {"d","e"}>> x.union(y)

Page 40: Datastructures in python

• issubset

>>> x = {"a","b","c"}>>> y = {"d","e"}>>> z = {"b","c"}>>> y.issubset(x)False>>> z.issubset(x)True

Page 41: Datastructures in python

• issuperset

>>> x = {"a","b","c","d"}>>> y = {"c", "d"}>>> x.issuperset(y)True>>> y.issuperset(x)False

Page 42: Datastructures in python

• pop()

• Remove and return an arbitrary set element.

>>> x = {"a","b","c","d"}>>> x.pop()>>> ‘a’

Page 43: Datastructures in python

Questions ?

Page 44: Datastructures in python

• Sample text file for list operations:URL : http://bit.ly/2bnUBje

Using this text file to make a list of words, and find the no.of words in the file, make a ‘Set’ of words (which will be a set of unique words). Find the no.of unique words. Make a dictionary of word – count , i.e word as key and count as value.

• Sample text file with name,email pairURL : http://bit.ly/2bNGBPD

Read this text file it contains , name and email . Read this text make a list and Then make a dictionary with name – email as key – value.

Page 45: Datastructures in python

• Subscribe Mailing List:URL : https://mail.python.org/mm3/mailman3/lists/hydpy.python.org/

• Meetup page:URL : https://www.meetup.com/Hyderabad-Python-Meetup-Group/

• FacebookURL : https://www.facebook.com/HydPy/

Connect