YouTube

Got a YouTube account?

New: enable viewer-created translations and captions on your YouTube channel!

English subtitles

← Lookup - Web Development

Get Embed Code
4 Languages

Showing Revision 10 created 05/25/2016 by Udacity Robot.

  1. So we've got this function, build link index, that makes our index.
  2. We just wrote this together.
  3. Let's use this new index function.
  4. So the first thing I want to do is actually run the function and store that somewhere.
  5. So we'll store that in a variable called link index=build link index.
  6. Now, this isn't the best Python code.
  7. Normally we wouldn't use global variables like this, but this is fine for this example.
  8. One time, we're going to build this link index.
  9. And now I'd like to update our link by id function
  10. to use our new index.
  11. Okay, so I've improved this function
  12. to instead of iterating over the entire list of links,
  13. to just look up the link id in the index.
  14. And let's give this a test.
  15. Okay, so let's call this function link by id(24).
  16. We've done that a couple times. I click run.
  17. Ah, and we see our link--id=24.
  18. Now, what happens if we run this on a link that doesn't exist?
  19. Barf!
  20. Our program died because we tried to look up,
  21. in a Python hashtable, an ID that doesn't exist--
  22. or a key that doesn't exist.
  23. So there's an easy way to fix that in Python.
  24. I'll show you how to do that.
  25. Instead of using these braces, we can use the function called get,
  26. which Python hashtables have.
  27. And what this does is it checks to see if this key is in the hashtable,
  28. and if it is, that's what this function returns; otherwise, it returns none.
  29. So let's give our function a test again by running this.
  30. Okay, now we return none.
  31. Very cool. That's what we expected.
  32. And let's just make sure that our function is still working the way it worked before
  33. by sending in a link that we know exists.
  34. In this case, I'll do 4. Here we go.
  35. So we see link id 4.
  36. So now we have this function link by id
  37. that uses our index.
  38. So if we had a bunch of links,
  39. all we'd have to do is build this index once,
  40. and then we don't have to scan over it every time we do a lookup--every time we do a query.
  41. Instead we can just hit the index.
  42. Okay, now there's one last function I'd like you to add.
  43. What I'd like you to do is implement this new function called add new link.
  44. It's going to take a link--it's going to take an instance of link--as a parameter,
  45. and then it needs to both add the link to our database--
  46. which is this list object we've been working with links--
  47. and it's also going add the links id
  48. to the list--the link index.
  49. Go ahead and implement this function now.