policy:
context: growth rate of an algorithm
Ref:
Q: Return the indexes of two numbers in an unsorted list that adds up to a target value.
Assume that:
Example:
Say the list is [7, 2, 4, 3, -1] and the target value is 5.
In this case, the numbers at index positions 1 and 3 add up to the target number (5), so the answer is (1, 3)
Solution:
In [14]: def two_sum(a_list, target): a_dict = {} for index, value in enumerate(a_list): reminder = target - value if reminder in a_dict: return [a_dict[reminder], index] else: a_dict[value] = index In [15]: a = [7, 2, 4, 3, -1] In [16]: two_sum(a, 5) Out[16]: [1, 3]
Ref:-
The Self-Taught Computer Scientist The Beginner's Guide to Data Structures & Algorithms By Cory Althoff 2021
→ Chapter 13 Hash Tables → Two Sum → pages 143-144.