Professional Documents
Culture Documents
Chapter-5:
Data Structures and Algorithms
5.1 Tuples, Dictionaries, Sets
Introduction
●
Every computer program uses data structures and algorithms
Data
DataStructures
Structures Data-centric view of the world
Why?:
Why?:organize
organizeyour
yourdata
datainin
computer's Advanced data structures
computer'smemory
memoryto toefficiently
efficiently
store
storeand
andretrieve
retrieveinformation
information
Basic ‘non-numerical’ algorithms
How?:
How?:using
usingarrays,
arrays,lists,
lists,stacks,
stacks, acting on database (searching,
queues,
queues,trees,
trees,matrix,
matrix,etc.
etc. sorting, etc.)
Trees General-
Unsorted list
(BST,CBT,RBT) purpose
Array
(1d,2d,etc.)
Sorted list Hash-Tables
●
So far, we have seen: lists and arrays (via numpy)
●
Python offers other native data structures: tuples, dictionary and sets
Python Data Structures- Tuples
●
just like lists, tuples represent sequences of objects.
●
unlike lists, they are immutable. Once created, you cannot modify their
content.
●
How to create a tuple?
tup1 = (1, 2, 3, 4, 5 ) # tuple of integer
tup2 = ("a", "b", "c", "d") # tuple of string
tup3 = (True,False,True) # tuple of boolean
tup4 = () #empty tuple
tup5 = (122,) #tuple with one item
Remarks:
– Parentheses are optional but recommended (convention). As a reminder lists use
square brackets [ ].
– Like list, tuples can contain sequences of customized objects.
– The empty tuple is written as two parentheses containing nothing.
– Warning: one must include a comma if the tuple contains a single value !
Python Data Structures- Tuples
●
Accessing values in tuples
tup1 = (1, 2, 3, 4, 5 ) 1
– indices work like list. Example: print(tup1[0]) (2, 3)
print(tup1[1:3])
tup1 = (1, 2, 3, 4, 5 )
●
Reassigning & Removing items => this is not permitted tup1[0]=1
del tup1[1]
●
Basic Operations permitted with Tuples:
Python Data Structures- Tuples
●
Some built-in functions tup1 = (1,2,3,4,5)
print(len(tup1)) 5
print(max(tup1)) 5
print(min(tup1)) 1
list1=[6,7,8,9,10] (6, 7, 8, 9, 10)
tup2=tuple(list1) #convert list to tuple
print(tup2)
●
Why Tuples??
– use tuple instead of list if you do not plan to reassign the items
– It is used everywhere within Python. Some examples:
# multiple assignment
a,b,c= 1, 3, "Hello" # comma separated value
# this is the same as print("Hello %s %s"%("ECE",122))
tup1=(1,3,"Hello")
a,b,c=tup1
Python Data Structures- Tuples
●
Important Application: function with multiple return values!
def three_power_of_x(x):
return x, x**2, x**3
0 (0, 0, 0)
def operate_string(a): 1 (1, 1, 1)
return a.lower(),a.upper() 2 (2, 4, 8)
3 (3, 9, 27)
# Main program 4 (4, 16, 64)
for i in range(5): ('hello', 'HELLO')
print(i,three_power_of_x(i)) hello HELLO
tup1=operate_string("Hello")
print(tup1)
s1,s2=operate_string("Hello")
print(s1,s2)
●
List of tuples are also possible (useful for coordinates, for example)
coordinates=[(1,2),(3,4),(5,6)]
Python Data Structures- Dictionary
●
Dictionary also represents a sequence of values
●
Unlike lists or tuples, items are not identified by their indices but using a key
●
Each item is defined by key:value (keys are immutable and must be different)
●
Items are separated by commas and the whole sequence is within {}
●
How to create a Dictionary?
d1= {1:"Monday",2:"Tuesday",3:"Wednesday"} # key could be number
d2 ={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday"} # key could be string
d3 ={("Mon",1):"Monday",("Tue",2):"Tuesday",("Wed",3):"Wednesday"}#using key tuple
d4 ={"Mon":1,"Tue":2,"Wed":3} # values could be whatever types we want
d5={} # an empty dictionary
# Add new values inside dictionary
d5["Mon"]="Monday"
d5["Tue"]="Tuesday"
d5["Wed"]="Wednesday"
print(d5)
{'Mon': 'Monday', 'Tue': 'Tuesday', 'Wed': 'Wednesday'}
Python Data Structures- Dictionary
●
Accessing values in Dictionary
d ={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday"} Monday
print(d["Mon"]) # possible approach Monday
print(d.get("Mon")) # preferred approach Cannot find value
print(d.get("Fri","Cannot find value")) # can include default value False
print("Fri" in d) # check if key is valid
●
Deleting values in Dictionary
d ={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday"}
del d["Mon"] # remove entry with key 'Mon'
d.clear() # remove all entries in d
del d # delete entire dictionary
●
“Regrouping” Dictionaries
d1 ={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday"}
d2 ={"Thu":"Thursday","Fri":"Friday","Sat":"Saturday"}
d1.update(d2) # add d2 into d1
print(d1) {'Mon': 'Monday', 'Tue': 'Tuesday', 'Wed': 'Wednesday', 'Thu': 'Thursday', 'Fri': 'Friday', 'Sat': 'Saturday'}
Python Data Structures- Dictionary
●
Scanning the keys
d ={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday"} Mon
for key in d.keys(): Tue
print(key) Wed
●
Scanning the values
d ={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday"} Monday
for value in d.values(): Tuesday
print(value) Wednesday
●
Scanning both keys and values
Mon Monday
d ={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday"}
Tue Tuesday
for key,value in d.items():
Wed Wednesday
print(key,value)
Python Data Structures- Dictionary
●
Application: counting occurrences
# initialize dictionary and sentence
counts={}
phrase="The most certain way to succeed is always to try just one more time".lower()
# scan over letters and fill-up dictionary with letter occurrences
for let in phrase:
if let in counts:
counts[let]=counts[let]+1
elif let!=" ":
counts[let]=1
print(counts)
{'t': 8, 'h': 1, 'e': 7, 'm': 3, 'o': 5, 's': 5, 'c': 3, 'r': 3, 'a': 4, 'i': 3, 'n': 2, 'w': 2, 'y': 3, 'u': 2, 'd': 1, 'l': 1, 'j': 1}
Python Data Structures- Sets
●
A set represents a sequence of values which is unordered and unindexed
●
Like dictionary it uses curly bracket {}
●
Each item must be unique and immutable, but the set is itself is mutable
s1 = {"apple", "banana", "cherry"}
print(s1)
s2 = {4,2,3,1,5}
print(s2) {'banana', 'apple', 'cherry'}
s3=set() # empty set – {} is used for empty dictionary {1, 2, 3, 4, 5}
s3.add("apple") {'banana', 'cherry'}
s3.add("banana") True
s3.add("cherry") {'a', 'p', 'e', 'l'}
s3.remove("apple")
print(s3)
print("cherry" in s3)
word="apple"
s4=set(word) # create set of letters (no duplicate allowed)
print(s4)
Python Data Structures- Sets
●
Applications: Mathematical set operations like union, intersection, difference
and symmetric difference. We can do this with operators or methods.
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
# union
print(a | b) # b.union(a) or a.union(b) good too
# intersection
print(a & b)
# difference
print(a - b)