-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path004. Sum of two numbers(Hash and enumerate)
More file actions
63 lines (52 loc) · 1.71 KB
/
004. Sum of two numbers(Hash and enumerate)
File metadata and controls
63 lines (52 loc) · 1.71 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
# Sum of two numbers
# A: Hash (Dictionary)
def two_sum (nums,target):
num_dict = {} # Create a dictionary to store elements and their indices
for i, num in enumerate(nums):
complement = target - num # Calculate another number needed
if complement in num_dict: # If another number is found in the dictionary, return their index
return [num_dict[complement], i]
else:
num_dict[num] = i
return ()
nums = [2, 7, 11, 15]
target = 26
print(two_sum(nums,target))
# Example
nums = [2, 7, 11, 15]
target=26
result = two_sum(nums, target)
print(result) # Output: [2, 3]
# B: Mine method:
# Error: Trying to use for j in lst[i:] in a nested loop, this is not the correct approach. In this context, i is an element in the list list_1, not an index, so writing lst[i:] causes an error.
def find_add(lst):
aim = input()
aim = int(aim)
lst_len = len(lst)
for i in lst:
for j in lst[i:]:
if i + j == aim:
index_1 = lst.index(i)
index_2 = lst.index(j)
return index_1, index_2
list_1 = (1,2,3,4,5,6,7,8)
find_add(list_1)
# correct:
def find_add(lst):
aim = input()
aim = int(aim)
lst_len = len(lst)
index_1 = -1 #The initial index is -1, indicating that no matching element was found
index_2 = -1
for i in range(lst_len):
for j in range(i + 1, lst_len):
if lst[i] + lst[j] == aim:
index_1 = i
index_2 = j
break
if index_1 != -1:
break # If a matching element is found, exit the outer loop
return index_1, index_2
list_1 = [1, 5, 7, 10]
result = find_add(list_1)
print(result)