Upload
yi-lung-tsai
View
420
Download
3
Embed Size (px)
Citation preview
PROBLEM SOLVING WITH ALGORITHMS AND DATA STRUCTURES — LISTSBruce Tsai
http://interactivepython.org/runestone/static/pythonds/BasicDS/Lists.html
LIST
Unordered list
Collection of items where each item holds a relative position with respect to the others
[54, 26, 93, 17, 77, 31]
2
UNORDERED LIST COMPLEXITY
add(item) — O(1)
remove(item) — O(n)
search(item) — O(n)
isEmpty() — O(1)
size() — O(n)
append(item) — O(n)
index(item) — O(n)
insert(pos,item) — O(pos)
pop() — O(n)
pop(pos) — O(pos)
3
ORDERED LIST
Collection of items where each item holds a relative position that is based upon some underlying characteristic of the item
Ascending or descending
[54, 26, 93, 17, 77, 31] => [17, 26, 31, 54, 77, 93]
4
ORDERED LIST COMPLEXITY
add(item) — O(n)
remove(item) — O(n)
search(item) — O(n)
isEmpty() — O(1)
size() — O(n)
index(item) — O(n)
pop() — O(n)
pop(pos) — O(pos)
5
SELF CHECK
1. Implement the append method for UnorderedList. What is the time complexity of the method you created?
2. In the previous problem, you most likely created an append method that was O(n). If you add an instance variable to the UnorderedList class you can create an append method that is O(1). Modify your append method to be O(1).
6
PART 1
Append method adds a new item to the end of the list making it the last item in the collection.
First traverse UnorderedList to original last item and then set new item as next node of original last item
The time complexity is O(n)
7
PART 2
Add instance variable tail to represent the last item
https://gist.github.com/wagamama/18a75738f7dd3dcdf817#file-unorderedlist-py
8
DISCUSSION QUESTIONS
7. What is the result of carrying out both steps of the linked list add method in reverse order? What kind of reference results? What types of problems may result?
8. Explain how the linked list remove methods works when the item to be removed is in the last node.
9. Explain how the remove method works when the item is in the only node in the linked list.
9
NO. 7
NO. 8
previous current
NO. 9
previous == None
self.head = current.getNext()
self.head = None
12
ARRAY (SEQUENCE)
Allocate size first
Item with index
assign — O(1)
insert — O(n)
delete — O(n)
PYTHON LIST COMPLEXITY
append — O(1)
insert — O(n)
delete — O(n)
search — O(n)
size — O(1)
get — O(1)
set — O(1)
14
REFERENCE
http://interactivepython.org/runestone/static/pythonds/BasicDS/Lists.html
https://gist.github.com/wagamama/18a75738f7dd3dcdf817
http://www.csie.ntnu.edu.tw/~u91029/Sequence.html
https://wiki.python.org/moin/TimeComplexity