[Python] A program that finds a pair that can be divided by a specified value

[Python] A program that finds a pair that can be divided by a specified value

This is a memo for myself.

▼ Question

--A list containing positive integers is given. (Ar) --Extract two integers from the list and find the number of pairs whose total value is divisible by k (positive integer).

URL

▼sample input

python


k=3
ar=[1,3,2,6,1,2]

▼sample output

python


5

image.png

▼my answer

python


def divisibleSumPairs(n, k, ar):
    ans = 0
    
    for n,i in enumerate(ar):
        arr=[]
        arr =list(map(lambda x:(x+i)%k, ar[n+1:]))
        ans += arr.count(0)
    return ans

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    nk = input().split()
    n = int(nk[0])
    k = int(nk[1])
    ar = list(map(int, input().rstrip().split()))
    result = divisibleSumPairs(n, k, ar)
    fptr.write(str(result) + '\n')
    fptr.close()

##### Way of thinking ――Produce all patterns of combinations. --Calculate the remainder of dividing each element by k. --Add up the number with remainder = 0.

▼ Excludes combinations that have been crossed once.

python


for n,i in enumerate(ar):
    print(ar[n+1:])

#------------------
[3, 2, 6, 1, 2]
[2, 6, 1, 2]
[6, 1, 2]
[1, 2]
[2]
[]

** ・ map function ** map (function, iterable)

Extracts the iterable elements one by one and returns the value of the function execution.

▼ Use in such cases -I want to multiply each element of list by n. -Often used with lambda expressions. └ lambda expression: A function (def) written in one sentence

▼ Processing Processing that combines a for statement and a function.

▼ Caution The output value is map type. If you want list, convert it with list ().


** ・ lambda expression ** A simplified version of the function defined by def. Describe the arguments and processing in one sentence without giving a method name.

lambda argument: processing


** ・ map and lambda ** `map (lambda variable: processing, iterable)`

Extract the iterable elements one by one, put them in the lambda variable, and execute the process. This process is performed for each element.

** ・ enumerate function ** ・ Used in for statements ・ Extract the index number

for variable 1, variable 2 in enumerate (iterable): └ Variable 1: Enter the index number. └Variable 2: The extracted element is entered.

▼ Use in such cases ・ I want to know how many times for is processed.

It seems difficult because I'm not familiar with English and it's long, but it's actually simple.

Normal for statement: "for variable 2 in iterable" ① Add a variable to put the index number (write in the other party) ② Enclose the iterable with enumerate.

Recommended Posts

[Python] A program that finds a pair that can be divided by a specified value
[Python] A program that finds the maximum number of toys that can be purchased with your money
How to install a Python library that can be used by pharmaceutical companies
A program that sends a fixed amount of mail at a specified time by Python
[Python] A program that creates a two-dimensional array by combining integers
[Python] A program that finds the most common bird types
Implement a thread that can be paused by exploiting yield
[Python] A program to find the number of apples and oranges that can be harvested
[Python] Make a graph that can be moved around with Plotly
Investigation of DC power supplies that can be controlled by Python
I made a shuffle that can be reset (reverted) with Python
From a book that programmers can learn (Python): Statistical processing-deviation value
Understand the probabilities and statistics that can be used for progress management with a python program
[Python] A program that creates stairs with #
A program that plays rock-paper-scissors using Python
[Python] A program that rounds the score
I created a template for a Python project that can be used universally
[Python] A program that calculates the number of socks to be paired
From a book that programmers can learn (Python): Conditional search (maximum value)
A class for PYTHON that can be operated without being aware of LDAP
I want to create a priority queue that can be updated in Python (2.7)
A program that removes duplicate statements in Python
I made a familiar function that can be used in statistics with Python
[Python] A program that finds the minimum and maximum values without using methods
[Python] A program that finds the shortest number of steps in a game that crosses clouds
How to create a property of relations that can be prefetch_related by specific conditions
A mechanism to call a Ruby method from Python that can be done in 200 lines
[Python] A program that counts the number of valleys
Python knowledge notes that can be used with AtCoder
From a book that programmers can learn ... (Python): Pointer
[Python] A program that compares the positions of kangaroos.
List the classes that can be referenced by ObjCClass
A Python program that converts ical data into text
How to set up a simple SMTP server that can be tested locally in Python
Convert mesh data exported from SpriteUV2 to a format that can be imported by Spine
A Python program in "A book that gently teaches difficult programming"
From a book that programmers can learn ... (Python): About sorting
From a book that programmers can learn (Python): Decoding messages
I tried "a program that removes duplicate statements in Python"
Scripts that can be used when using bottle in Python
Precautions that must be understood when building a PYTHON environment
A Python program that aggregates time usage from icalendar data
Let's make a diagram that can be clicked with IPython
Evaluation index that can be specified in GridSearchCV of sklearn
[Python] Draw elevation data on a sphere with Plotly and draw a globe that can be rotated round and round
[Python] A program that compares each element of list one by one and wins or loses. zip ()
・ <Slack> Write a function to notify Slack so that it can be quoted at any time (Python)
Newcomer training program by Python
Create a program that can generate your favorite images with Selenium
[Python] I made my own library that can be imported dynamically
I made a package that can compare morphological analyzers with Python
A record that GAMEBOY could not be done in Python. (PYBOY)
Created a library for python that can easily handle morpheme division
About psd-tools, a library that can process psd files in Python
Make a Spinbox that can be displayed in Binary with Tkinter
From a book that programmers can learn (Python): Find the mode
From a book that programmers can learn ... (Python): Review of arrays
A timer (ticker) that can be used in the field (can be used anywhere)
[Ev3dev] Create a program that captures the LCD (screen) using python
A program that determines whether a number entered in Python is a prime number
[Python algorithm] A program that outputs Sudoku answers from a depth-first search