Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # UNIT 2 Problem Set - Question 6
- # Define a procedure, find_last, that takes as input
- # two strings, a search string and a target string,
- # and returns the last position in the search string
- # where the target string appears, or -1 if there
- # are no occurrences.
- #
- # Example: find_last('aaaa', 'a') returns 3
- # Make sure your procedure has a return statement.
- def find_last(search, target):
- search_len = int(len(search))
- target_len = int(len(target))
- if (search.find(target)) == (-1):
- return -1
- search = search[::-1]
- target = target[::-1]
- last_char = search.find(target)
- flip_first = last_char + target_len
- first_char = search_len - flip_first
- return first_char
- sentence = "when I go walking, after midnight, out in the starlight"
- target = "ight"
- print (find_last(sentence,target))
- #note str length is no. characters whereas position no. character starts at zero
- #note above approach reverses both strings
- #first char last occurrence target str, if reversed, is last char first occurrence in reversed search str
- #easy to find first character first occurence of reversed target str in reversed search string
- #then, arithmetic using string lengths
- #add target str length to position no. first char reversed target str first occurrence in reversed search str
- #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