Assignment 3.1: Linked List (5 points)
Implement the linked list data structure in Python. Create a class Node which stores the data and link to another Node class. Create also the class LinkedList which maintains the linked list created by Node classes and has the following methods:
- append(data: object): inserts a new Node containing the data to the end of the list.
- insert(data: object, index: int): inserts a new Node containing the data to the position indicated by the index (the index of the first node is 0).
- delete(index: int): deletes a node from the position indicated by the index.
- index(data: object): search the Node containing the data and returns its index. Returns \(-1\) if not found.
- print(): prints the content of linked list (format: node1 -> node2 -> node3).
A code template with an example program:
class Node:
# TODO
class LinkedList:
# TODO
if __name__ == "__main__":
L = LinkedList()
L.append(1)
L.append(3)
L.print() # 1 -> 3
L.insert(10, 1)
L.insert(15, 0)
L.print() # 15 -> 1 -> 10 -> 3
print(L.index(1)) # 1
L.delete(0)
L.print() # 1 -> 10 -> 3
Submit your solution in CodeGrade as linked.py.
Assignment 3.2: Binary Search (3 points)
Implement the binary search algorithm in Python. Create a function search(A: list, item: int) which returns the index of the item in the list. If the item is not found the function returns \(-1\). You can assume that the list contains only
integers and it is always sorted.
Limits:
- Integers in the list are between \(1...10^6\)
- The maximum length of the list is \(10^6\)
Target: the algorithm performs in \(\Theta(\log(n))\) time.
A code template with an example program:
def search(A: list, item: int):
# TODO
if __name__ == "__main__":
A = [1, 2, 3, 6, 10, 15, 22, 27, 30, 31]
print(search(A, 6)) # 3
print(search(A, 7)) # -1
print(search(A, 30)) # 8
Submit your solution in CodeGrade as binarysearch.py.