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).
▼sample input
python
k=3
ar=[1,3,2,6,1,2]
▼sample output
python
5
▼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()
▼ 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 argument: processing
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