Guest User

Untitled

a guest
Jan 18th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. # UNIT 2 Problem Set - Question 6
  2. # Define a procedure, find_last, that takes as input
  3. # two strings, a search string and a target string,
  4. # and returns the last position in the search string
  5. # where the target string appears, or -1 if there
  6. # are no occurrences.
  7. #
  8. # Example: find_last('aaaa', 'a') returns 3
  9.  
  10. # Make sure your procedure has a return statement.
  11.  
  12. def find_last(search, target):
  13. search_len = int(len(search))
  14. target_len = int(len(target))
  15. if (search.find(target)) == (-1):
  16. return -1
  17. search = search[::-1]
  18. target = target[::-1]
  19. last_char = search.find(target)
  20. flip_first = last_char + target_len
  21. first_char = search_len - flip_first
  22. return first_char
  23.  
  24. sentence = "when I go walking, after midnight, out in the starlight"
  25. target = "ight"
  26. print (find_last(sentence,target))
  27.  
  28. #note str length is no. characters whereas position no. character starts at zero
  29. #note above approach reverses both strings
  30. #first char last occurrence target str, if reversed, is last char first occurrence in reversed search str
  31. #easy to find first character first occurence of reversed target str in reversed search string
  32. #then, arithmetic using string lengths
  33. #add target str length to position no. first char reversed target str first occurrence in reversed search str
  34. #logic is position no. in reversed str deducted from search str length gives position no. in original search str
Add Comment
Please, Sign In to add comment