Data Structures - Student Version
Data Structures - Student Version
Chris Rowlands
Stuff-I-got-interested-in-this-week group
Data Structures
Learning outcomes
• Understand what a data structure is
• Be able to select a suitable data structure based on some simple
requirements
• Be familiar with arrays, linked lists and hash tables
• Be able to use all of Python’s built-in data structures (list, tuple, dict, set,
frozenset)
Data Structures
Outline
• Introduction to data structures
– Arrays
– Linked lists
• Python data structures
– Lists
– Tuples
– Dicts (hash tables)
– Sets
Data Structures
Arrays
• How would you store a monochrome 2D image
in memory efficiently?
– Each pixel has the same bit depth
– Store each pixel in row 1, then row 2, etc.
• Just need to know where the first element is,
plus the height, width and bit depth!
– Plus data type in a general case…
• Can work for 3D, 4D etc. data too.
Data Structures
Arrays
• Pros:
– Memory efficient (little overhead, ~100% use of space)
– Fast to read / write (easy to calculate where each pixels is in memory)
• Cons:
– Can’t resize the array quickly (or add a new element in the middle easily)
– Can’t have elements of different data types, or lengths
– Generally requires large, contiguous blocks of memory
• Python doesn’t natively support arrays, strangely.
Data Structures
Linked lists
• Each node has the address of the next
• Nodes can be anywhere in memory
– No need for large contiguous blocks
– Nodes can be different sizes if needed
– Resizing the structure is easy
• BUT:
– Traversing the structure is slow
– There is substantial memory overhead
Data Structures
Quiz
Starting with this list:
myList = [0,1,2,3,4,5,6,7,8,9]
Which slice parameters will produce the following output?
[2,3,4,5]
[7,5,3,1]
Hash tables
• How quickly can you look up
someone’s number in a phone book?
– log(N) operations
• Determine the address of the data
using a hash function
– Only one operation needed!
Data Structures
0
1 1
0 0
1 0
1 0
1 1
0 1
0 0
1 46
FC
A9
8F
Data Structures
phonenumbers = {
"Emergency services": '0118 999 88199 9119725
3',
"Annoying directory enquiries": '118 118',
"Jenny": '867-5309',
"Dr Turk": '916-225-5887'
}
print(phonenumbers["Jenny"])
867-5309
Data Structures
Set operators
• Union (everything in set A or set B): A|B
– No duplicate elements
• Intersection (only elements which are in both sets): A&B
• Difference (elements in A that aren’t in B): A-B
• Symmetric difference (elements in A and B but not in both): A^B
Data Structures
Summary
• Learned what a data structure is, and some classic examples
– Array, linked list, hash table
• Learned how to use Python’s built-in data structures
– Lists and tuples, including slicing
– Dicts
– Sets and frozensets, including set operators