English subtitles

← Find Last Solution - Intro to Computer Science

Get Embed Code
6 Languages

Showing Revision 7 created 05/24/2016 by Udacity Robot.

  1. This problem asks you to define a function
  2. called "find_last" that takes in 2 parameters:
  3. one string that we're searching in, another string that we're finding.
  4. The whole point of this function
  5. is to find the position of the last occurrence of "t".
  6. So let's use a variable called "last_pos".
  7. The overall plan here
  8. is while we keep finding occurrences of "t",
  9. we're going to keep running the "find" function
  10. and updating our offset.
  11. So let's do that: "while True:"--
  12. and since we don't know when we want to terminate yet,
  13. we're going to update a position
  14. using the "find" function,
  15. where we're searching for "t",
  16. but we're starting at the last position, plus 1.
  17. The "+1" is important so that we
  18. don't keep finding the same string over and over again.
  19. If this returns "-1",
  20. that means we didn't find another occurrence of "t".
  21. So we want to return the previous refound occurrence,
  22. which we stored in "last_pos".
  23. Otherwise, we want to update "last_pos"
  24. with the position that we just found.
  25. So the one thing left is: what do we initialize "last_pos" to?
  26. If we never find any occurrence of "t" in "s",
  27. the goal is to return "-1".
  28. So if "position" equals negative 1
  29. in the first iteration, we're just going to return "last_pos".
  30. So it makes sense to initialize it to "-1".