Using Python: write a function that takes two arguments: (1) a target item to fi
ID: 3755113 • Letter: U
Question
Using Python: write a function that takes two arguments: (1) a target item to find, and (2) a list. Your function should return the index (offset from 0) of the last occurrence of the target item or None if the target is not found. E.g. the last occurrence of 33 is at offset 3 in the list [ 42, 33, 21, 33 ] because 42 is offset 0, the first 33 is at offset 1, 21 is offset 2, and the last 33 is offset 3.
Use unittest to test your function with several different target values and lists.
Next, test your function with a character as the target, and a string as the list, e.g. find('p', 'apple'). What should happen?
Be sure to use unittest to demonstrate that your code works properly.
Explanation / Answer
def find(target, lst): last_index = None for i in range(len(lst)): if lst[i] == target: last_index = i return last_index import unittest class TestFind(unittest.TestCase): def test_with_string(self): self.assertTrue(find(33, [42, 33, 21, 33]) == 3) def test_with_numbers(self): self.assertTrue(find('p', 'apple') == 2) unittest.main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.