CP164 Study Guide - Midterm Guide: Linear Search, Data Element

36 views2 pages
14 Jun 2018
School
Course
Professor
The Array-Based List Implementation
Implementing the Python __setitem__ method allows us to use the square bracket / index
syntax to assign a value to a List, like this:
movie_list[n] = movie
The method is:
def __setitem__(self, i, value):
"""
---------------------------------------------------------
Places a copy of value into the list at position n.
Use: l[i] = value
-------------------------------------------------------
Preconditions:
i - index of the element to access (int)
value - a data value (?)
Postconditions:
The i-th element of list contains a copy of value. The existing
value at i is overwritten.
-------------------------------------------------------
"""
assert self._valid_index(i), "Invalid index value"
self._values[i] = deepcopy(value)
return
As above, only valid indices are allowed.
The _linear_search Method
The linear search method is a private helper method. A helper method is an method that is
not called from outside the class it is defined in, but rather, is used by other methods within
that class. This is particularly useful when the actions it performs are used by multiple
other functions. The linear search in particular is used by the re move and index methods to
find the index of a key in the List. The methods then do different things with that
information.
def _linear_search(self, key):
"""
-------------------------------------------------------
Searches for the first occurrence of key in the list.
Private helper method - used only by other ADT methods.
Use: i = self._linear_search(key)
-------------------------------------------------------
Preconditions:
key - a partial data element (?)
Postconditions:
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in