-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtwo_sum_problem.py
More file actions
98 lines (39 loc) · 1.5 KB
/
Copy pathtwo_sum_problem.py
File metadata and controls
98 lines (39 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# You are given an array of numbers and a target sum. Your task is to find the indices of the two numbers that add up to the target
nums_list = [4,2,7,8,1]
target = 9
def sum_problem(nums_list, target):
# create a empty dictionary
num_dict = {}
#iterate through the list using enumerate
for index, num in enumerate(nums_list):
complement = target - num
if complement not in num_dict:
num_dict[num] = index
else:
return [num, complement]
return []
sum_problem(nums_list, target)
def sum(nums_list, target):
num_dict = {} #define a dictionary
for index, num in enumerate(nums_list): #iterate over the list and keep both the index and the number
complement = target - num
if complement in num_dict:
return [num_dict[complement], index]
num_dict[num] = index
return []
print(sum(nums_list, target)[:])
# nums = [2, 7, 11, 15]
# target = 9
# answer_list = []
# for member_index in range(len(nums)):
# if nums[member_index] > 9:
# continue
# else:
# for next_index in range(len(nums[member_index+1: ])):
# if nums[next_index] > 9:
# continue
# elif (nums[member_index] + nums[next_index]) == 9:
# if nums[member_index] not in answer_list :
# answer_list.append(member_index)
# answer_list.append(next_index)
# print(answer_list)