How to realize the addition of array elements by python
Most people do not understand the knowledge points of this article "python how to achieve the pairwise addition of array elements", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "python how to achieve the pairwise addition of array elements" article.
Array elements add count = 0c2 = [] for i in range (len (c)): if count = = 0: mm = c [I] # print (mm) # print (count) if count = = 1: print (c [I]) value = c [I] + mm c2 = np.append (c2) Value) count = 0 mm = 0 value = 0 continue count = count + 1
C is the original array, we set a count, when count=0 we do not operate, when count=1 we add the current element to the previous element.
Count=0 is actually odd, and count=1 is even.
Find the combination (Python implementation) in which the sum of two pairs is equal to 20 in the array
Find the combination in the array where the sum of two pairs is equal to 20.
For example, given an array [1, 7, 17, 2, 6, 3, 14], there are two pairs of conditions in this array: 17320 and 61420.
Analysis
There are two steps:
First, the array is sorted by heap sort or quick sort, and the time complexity is O (nlogn).
Then the sorted array is traversed from front to back and from back to front, and the time complexity is O (n).
Suppose the subscript for traversing from front to back is begin, and the subscript for traversing from back to front is end.
When arr [begin] + arr [end]
< 20时,满足条件的数一定在[begin+1, end]之间; 当arr[begin] + arr[end] >20:00, the number that satisfies the condition must be between [begin, end-1]
When arr [begin] + arr [end] = 20:00, find a set of qualified numbers, and the rest of the combination must be between [begin-1, end-1].
The time complexity of the whole algorithm is O (nlogn).
Python implements #-*-coding:utf-8-*-def quick_sort (arr, left, right): "" Quick sort "" if left > = right: return low = left high = right p = arr [left] while left
< right: while left < right and arr[right] >= p: right-= 1 arr [left] = arr [right] while left < right and arr [left] sum: end-= 1 else: print ('% s% s'% (arr [begin], arr [end]) begin + = 1 end-= 1if _ name__ = ='_ main__': arr = [1,7,17,2,6 3, 14] find_sum (arr, 20) is the content of the article "how to add array elements by python". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.