Tip:
Highlight text to annotate it
X
So we've got this function, build link index, that makes our index.
We just wrote this together.
Let's use this new index function.
So the first thing I want to do is actually run the function and store that somewhere.
So we'll store that in a variable called link index=build link index.
Now, this isn't the best Python code.
Normally we wouldn't use global variables like this, but this is fine for this example.
One time, we're going to build this link index.
And now I'd like to update our link by id function
to use our new index.
Okay, so I've improved this function
to instead of iterating over the entire list of links,
to just look up the link id in the index.
And let's give this a test.
Okay, so let's call this function link by id(24).
We've done that a couple times. I click run.
Ah, and we see our link--id=24.
Now, what happens if we run this on a link that doesn't exist?
Barf!
Our program died because we tried to look up,
in a Python hashtable, an ID that doesn't exist--
or a key that doesn't exist.
So there's an easy way to fix that in Python.
I'll show you how to do that.
Instead of using these braces, we can use the function called get,
which Python hashtables have.
And what this does is it checks to see if this key is in the hashtable,
and if it is, that's what this function returns; otherwise, it returns none.
So let's give our function a test again by running this.
Okay, now we return none.
Very cool. That's what we expected.
And let's just make sure that our function is still working the way it worked before
by sending in a link that we know exists.
In this case, I'll do 4. Here we go.
So we see link id 4.
So now we have this function link by id
that uses our index.
So if we had a bunch of links,
all we'd have to do is build this index once,
and then we don't have to scan over it every time we do a lookup--every time we do a query.
Instead we can just hit the index.
Okay, now there's one last function I'd like you to add.
What I'd like you to do is implement this new function called add new link.
It's going to take a link--it's going to take an instance of link--as a parameter,
and then it needs to both add the link to our database--
which is this list object we've been working with links--
and it's also going add the links id
to the list--the link index.
Go ahead and implement this function now.