Have you ever wanted to compare the sum of each element with the value you specified when you had two lists? For example
[-1, 3, 8, 2, 9, 5] [4, 1, 2, 10, 5, 20]
Suppose you have two lists.
At that time, it is examined whether a specific value can be expressed by the sum of two elements selected from each list.
If a particular value is 25 and you select (-1, 4), the total is 3, which is different. In that case, only (5, 20) is correct. A YouTube video (see URL below) showed how to solve this problem. This time I wrote the method in Python.
I programmed three solutions from the methods introduced. The values to compare are ~~ 24, 25, 26 ~~ 23, 24, 25 (corrected December 13, 2019).
The first is how to add all the elements together.
Brute-force.py
#list
A = [-1, 3, 8, 2, 9, 5]
B = [4, 1, 2, 10, 5, 20]
#Value you want to compare
target = 24
#Brute force
for i in A:
for j in B:
if target - 1 <= (i + j) <= target + 1:
print(str(i) + "When" + str(j) + "Is a pair.")
The next method is to search the contents of the list and then compare.
linear.py
#list
A = [-1, 3, 8, 2, 9, 5]
B = [4, 1, 2, 10, 5, 20]
#Value you want to compare
target = 24
#Linear selection
for i, v in enumerate(B):
if target - 1 - v in A:
index = A.index(target - 1 -v)
print(str(A[index]) + "When" + str(v) + "Is a pair.")
if target - v in A:
index = A.index(target - v)
print(str(A[index]) + "When" + str(v) + "Is a pair.")
if target + 1 - v in A:
index = A.index(target + 1 - v)
print(str(A[index]) + "When" + str(v) + "Is a pair.")
Finally, how to create a matrix. The values to compare are 12, 13, 14.
Matrix.py
#Matrix creation
import numpy as np
#element
A = np.array([7, 4, 1, 10])
B = np.array([4, 5, 8, 7])
#Sort elements in ascending order
A.sort()
B.sort()
target = 13
#Table the addition of all elements
array = np.array([i+j for i in A for j in B]).reshape((len(A), len(B)))
#Target range
column_start = 0 #0
column_end = array.shape[1] #4
#search
for j in reversed(range(array.shape[0])):
#Upper range
for i in range(column_start, column_end):
if array[i][j] >= target - 1:
column_start = i
break
print(str(A[i]) + "When" + str(B[j]) + "Is a pair.")
I learned how to solve a problem with less computational complexity.
To be honest, I didn't know how to use the last method due to lack of study, I would like to continue learning programming. Thank you for visiting.
5 Problem Solving Tips for Cracking Coding Interview Questions (Link to YouTube video)
Recommended Posts