Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Now that we have an understanding of how linear search works conceptually let's implement it in code
Documentation
Language Implementations
For the implementation of linear search in other programming languages, check out the instruction step following this video.
If you want to continue with Python but don't have programming experience, check out our Beginning Python Track.
-
0:00
[MUSIC]
-
0:04
So far we've spent a lot of time in theory, and
-
0:07
while these things are all important things to know, you get a much
-
0:10
better understanding of how algorithms work when you start writing some code.
-
0:14
As I mentioned earlier, we're going to be writing Python code in this and
-
0:19
all subsequent algorithm courses.
-
0:21
If you do have programming experience but in another language,
-
0:25
check the Notes section of this video for an implementation in your language.
-
0:29
If you don't have any experience, I'll try my best to explain as we go along.
-
0:34
On the video you're watching right now, you should see a Launch Workspaces button.
-
0:39
We're going to use a Treehouse coding environment, called Workspaces,
-
0:43
to write all of our code.
-
0:45
If you're familiar with using Python in a local environment,
-
0:48
then feel free to keep doing so.
-
0:50
Workspaces is an in-browser coding environment, and we'll take care of all
-
0:55
the setup and installation so you can focus on just writing and evaluating code.
-
1:00
Workspaces is quite straightforward to use.
-
1:03
On the left here, we have a File Navigator pane,
-
1:06
which is currently empty since we haven't created a new file.
-
1:09
On the top, we have an Editor where we write all our code.
-
1:12
And then below that, we have a terminal, or a command line prompt,
-
1:16
where we can execute the scripts that we write.
-
1:19
Let's add a new file here.
-
1:20
So at the top, in the Editor area, we're going to go to File > New File.
-
1:24
And we'll name this linear_search.py.
-
1:31
In here,
-
1:32
we're going to define our linear_search algorithm as a stand-alone function.
-
1:37
We start with the keyword def, which defines a function or a block of code.
-
1:43
And then we give it the name, linear_search.
-
1:47
This function will accept two arguments.
-
1:49
First, the list we're searching through, and
-
1:52
then the target value we're looking for.
-
1:55
Both of these arguments are enclosed in a set of parentheses, and
-
1:59
there's no space between the name of the function and the arguments.
-
2:02
After that, we have a colon.
-
2:05
Now, there might be a bit of confusion here.
-
2:07
Since we already have this target value, what are we searching for?
-
2:11
And like the game we played at the beginning,
-
2:14
where John's job was to find the value, in a true implementation of linear_search,
-
2:19
we're looking for the position in the list where the value exists.
-
2:23
If the target is in the list, then we return its position.
-
2:27
And since this is a list, that position is going to be denoted by an index value.
-
2:32
Now, if the target is not found, we're going to return None.
-
2:35
The choice of what to return in the failure case may be different in other
-
2:39
implementations of linear_search.
-
2:41
You can return -1, since that isn't typically an index value.
-
2:46
You can also raise an exception, which is Python speak for
-
2:49
indicating an error occurred.
-
2:51
Now, I think for us,
-
2:52
the most straightforward value we can return here is None.
-
2:55
Now, let's add a comment to clarify this, so hit Enter to go to the next line.
-
2:59
And then we're going to add three single quotes,
-
3:04
and then below that on the next line, we'll say,
-
3:10
Returns the index position of the target if found, else returns None.
-
3:17
And then on the next line, we'll close off those three quotes.
-
3:20
This is called a docstring and is a Python convention for documenting your code.
-
3:25
The linear_search algorithm is a sequential algorithm that compares each
-
3:30
item in the list until the target is found.
-
3:33
To iterate, or loop, or walk through our list sequentially,
-
3:38
we're going to use a for loop.
-
3:40
Now, typically when iterating over a list in Python, we would use a loop like this.
-
3:45
We'd say for item in list.
-
3:48
This assigns the value at each index position to that local variable item.
-
3:53
We don't want this, though, since we primarily care about the index position.
-
3:58
Instead, we're going to use the range function in Python to create
-
4:03
a range of values that start at 0 and end at the number of items in the list.
-
4:08
So we'll say, for i, i stands for index here, in range,
-
4:13
starting at 0, and going all the way up to the length of the list.
-
4:19
We can get the number of items in the list using the len function.
-
4:23
Now, going back to our talk on complexity and
-
4:26
how individual steps in an algorithm can have its own run times,
-
4:29
this is a line of code that we would have to be careful about.
-
4:33
Python keeps track of the length of a list, so this function call here,
-
4:38
len(list), is a constant-time operation.
-
4:41
Now, if this were a naive implementation, let's say we wrote the implementation
-
4:46
of the list, and we iterate over the list every time we call this length function,
-
4:51
then we've already incurred a linear cost.
-
4:54
Okay, so once we have a range of values that represent indexed positions in this
-
4:59
list, we're going to iterate over that using the for loop and
-
5:02
assign each index value to this local variable i.
-
5:05
Using this index value,
-
5:07
we can obtain the item at that position using subscript notation on the list.
-
5:12
Now, this is also a constant-time operation because the language says so.
-
5:17
So we'll do if list, so once we have this value,
-
5:20
which we'll get by using subscript notation, so we'll say list[i].
-
5:24
Once we have this value, we'll check if it matches the target.
-
5:27
So if the value at i == target, well, if it does,
-
5:32
then we'll return that index value cuz we want the position.
-
5:37
And once we hit this return statement, we're going to terminate our function.
-
5:40
If the entire for loop is executed, and we don't hit this return statement,
-
5:45
then the target does not exist in the list.
-
5:47
So at the bottom here, we'll say return None.
-
5:51
Even though all the individual operations in our algorithm run in constant time,
-
5:56
in the worst-case scenario this for loop here will have to go through
-
6:00
the entire range of values and read every single element in the list.
-
6:05
Therefore giving the algorithm a big old value of N, or running in linear time.
-
6:10
Now, if you've written code before,
-
6:12
you've definitely written code like this a number of times, and I bet you didn't know
-
6:16
that all along you were implementing what is essentially a well-known algorithm.
-
6:20
So I hope this goes to show you that algorithms are a pretty
-
6:23
approachable topic.
-
6:25
Like everything else, this does get advanced, but
-
6:27
as long as you take things slow, there's no reason for it to be impossible.
-
6:31
Remember that not any block of code counts as an algorithm.
-
6:35
To be a proper implementation of linear_search, this block of code must
-
6:39
return a value, must complete execution in a finite amount of time, and
-
6:44
must output the same result every time for a given input set.
-
6:48
So let's verify this with a small test.
-
6:52
Let's write a function called verify that accepts an index value.
-
6:57
If the value is not None, it prints the index position.
-
7:00
If it is None, it informs us that the target was not found in the list.
-
7:04
So def verify, and this is going to take an index value.
-
7:09
And we'll say, if index is not None,
-
7:15
then we'll print Target found at index.
-
7:24
Whoops, that's a colon here.
-
7:27
Index, else, that needs to go back.
-
7:33
There we go, else, we'll say,
-
7:37
Target not found in list.
-
7:41
Okay, using this function, let's define a range of numbers now.
-
7:44
So this will be a list numbers, and we'll just go from 1 to, let's say, 10.
-
7:57
Now, if you've written Python code before, you know that I
-
8:00
can use a list comprehension to make this easier, but we'll keep things simple.
-
8:04
We can now use our linear_search function to search for
-
8:08
the position of a target value in this list.
-
8:10
So we can say result = linear_search.
-
8:15
And we're going to pass in the numbers list,
-
8:17
that's the one we're searching through.
-
8:19
And we want to look for the position where the value 12 exists.
-
8:23
And then we'll verify this result.
-
8:27
If our algorithm worked correctly,
-
8:29
the verify function should inform us that the target did not exist.
-
8:33
So make sure you save the file, which you can do by going up to File, and
-
8:37
Save, or hitting Cmd+S.
-
8:39
And then below in the terminal, you're gonna type out python linear_search,
-
8:45
or you can hit Tab and it should auto-complete, linear_search.py.
-
8:51
As you can see, correct, the target was not found in the list, so
-
8:54
the output of our script is what we expect.
-
8:57
For a second task, let's search for the value 6 in the list.
-
9:01
So you can copy this, Cmd+C to copy, and then paste it again, and
-
9:05
we'll just change 12 here to 6.
-
9:08
And then come back down to the terminal,
-
9:10
hit the up arrow to execute the same command again, and hit Enter.
-
9:14
You'll notice that I forgot to hit Save, so it did not account for that new change.
-
9:18
We'll try that again, and there you'll see that if it works correctly,
-
9:23
which it did, the index should be number 5.
-
9:26
Run the program on your end, and make sure everything works as expected.
-
9:30
Our algorithm returned a result in each case, it executed in a finite time, and
-
9:35
the results were the ones we expect.
-
9:37
In the next video, let's tackle binary search.
You need to sign up for Treehouse in order to download course files.
Sign up