Compare the sum of each element in two lists with the specified value in Python

Introduction

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.

program

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.")

What i learned

I learned how to solve a problem with less computational complexity.

in conclusion

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.

Reference URL

5 Problem Solving Tips for Cracking Coding Interview Questions (Link to YouTube video)

Recommended Posts

Compare the sum of each element in two lists with the specified value in Python
Get the index of each element of the confusion matrix in Python
How to count the number of occurrences of each element in the list in Python with weight
Tips: [Python] Calculate the average value of the specified area with bedgraph
Match the distribution of each group in Python
Find the divisor of the value entered in python
Get the sum of each of multiple columns with awk
Get the value of a specific key in a list from the dictionary type in the list with Python
Output the specified table of Oracle database in Python to Excel for each file
Check the operation of Python for .NET in each environment
Calculate the square root of 2 in millions of digits with python
Make a table of multiplication of each element in a spreadsheet (Python)
[Homology] Count the number of holes in data with Python
Get the number of occurrences for each element in the list
Get the value of a specific key up to the specified index in the dictionary list in Python
How to determine the existence of a selenium element in Python
Output the contents of ~ .xlsx in the folder to HTML with Python
Visualize the frequency of word occurrences in sentences with Word Cloud. [Python]
python note: map -do the same for each element of the list
Solve the subset sum problem with a full search in Python
Memo of the program to get the date in two digits with javascript, Ruby, Python, shell script
Count the number of times two values appear in a Python 3 iterator type element at the same time
Check the existence of the file with python
Display Python 3 in the browser with MAMP
The result of installing python in Anaconda
Test & Debug Tips: Create a file of the specified size in Python
The basics of running NoxPlayer in Python
Receive a list of the results of parallel processing in Python with starmap
Project Euler # 16 "Sum of Powers" in Python
Plot CSV of time series data with unixtime value in Python (matplotlib)
In search of the fastest FizzBuzz in Python
Get the return value of an external shell script (ls) with python3
[Python] Read the specified line in the file
Status of each Python processing system in 2020
[Python] Summary of functions that return the index that takes the closest value in the array
I installed Pygame with Python 3.5.1 in the environment of pyenv on OS X
To output a value even in the middle of a cell with Jupyter Notebook
Divides the character string by the specified number of characters. In Ruby and Python.
Turn multiple lists with a for statement at the same time in Python
Get the last element of the array by splitting the string in Python and PHP
How to get a list of files in the same directory with python
Output the number of CPU cores in Python
[Python] Get the files in a folder with Python
Load the network modeled with Rhinoceros in Python ③
[Python] Sort the list of pathlib.Path in natural sort
Prepare the execution environment of Python3 with Docker
2016 The University of Tokyo Mathematics Solved with Python
Project Euler # 10 "sum of prime numbers" in Python
Find the mood value with python (Rike Koi)
[Note] Export the html of the site with python.
Get the caller of a function in Python
[Automation] Extract the table in PDF with Python
Calculate the total number of combinations with python
Make a copy of the list in Python
Check the date of the flag duty with Python
Rewriting elements in a loop of lists (Python)
Compare the speed of Python append and map
Load the network modeled with Rhinoceros in Python ②
Find the solution of the nth-order equation in python
The story of reading HSPICE data in Python
[Note] About the role of underscore "_" in Python