Teaching Kids Programming: Videos on Data Structures and Algorithms
In Python, we can use the string.find method to search for a character: return the index of the first occurence if found or -1 if not found. This method applies to string only. We can implement such find method using the linear search.
1 2 3 4 5 6 7 | def find(s, target): if type(s) != str: raise Exception("only works on str") for i, v in enumerate(s): if v == target: return i return -1 |
def find(s, target): if type(s) != str: raise Exception("only works on str") for i, v in enumerate(s): if v == target: return i return -1
We use the enumerate function to access the index and value in a tuple/pair. The time complexity of a linear search is O(N) time where N is the number of the chracters in the string. And the space complexity is O(1).
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
231 wordsloading...
Last Post: C Macro/Function to Convert a IP Address into a 32-bit Integer
Next Post: Longest Distinct Sublist via Sliding Window (Two Pointer) Algorithm