python如何實(shí)現(xiàn)數(shù)組元素兩兩相加
數(shù)組元素兩兩相加
count = 0 c2 = [] 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是原數(shù)組,我們設(shè)置一個(gè)count,當(dāng)count=0時(shí)我們不操作,count=1時(shí)我們把當(dāng)前元素與前一元素相加。
count=0其實(shí)相當(dāng)于奇數(shù),count=1相當(dāng)于偶數(shù)
求數(shù)組中兩兩相加等于20的組合(Python實(shí)現(xiàn))
題目
求數(shù)組中兩兩相加等于20的組合。
例:給定一個(gè)數(shù)組[1, 7, 17, 2, 6, 3, 14],這個(gè)數(shù)組中滿足條件的有兩對(duì):17+3=20, 6+14=20。
解析
分為兩個(gè)步驟:
- 先采用堆排序或快速排序?qū)?shù)組進(jìn)行排序,時(shí)間復(fù)雜度為O(nlogn)。
- 然后對(duì)排序的數(shù)組分別從前到后和從后到前進(jìn)行遍歷, 時(shí)間復(fù)雜度為O(n)。
假設(shè)從前到后遍歷的下標(biāo)為begin,從后到前遍歷的下標(biāo)為end。
- 當(dāng)arr[begin] + arr[end] < 20時(shí),滿足條件的數(shù)一定在[begin+1, end]之間;
- 當(dāng)arr[begin] + arr[end] > 20時(shí),滿足條件的數(shù)一定在[begin, end-1]之間;
- 當(dāng)arr[begin] + arr[end] = 20時(shí),找到一組符合條件的數(shù),剩下的組合一定在[begin-1, end-1]之間。
整個(gè)算法的時(shí)間復(fù)雜度為O(nlogn)。
Python實(shí)現(xiàn)
# -*- coding:utf-8 -*- def quick_sort(arr, left, right): """快速排序""" 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] <= p: left += 1 arr[right] = arr[left] arr[left] = p quick_sort(arr, low, left-1) quick_sort(arr, left+1, high) def find_sum(arr, sum): """尋找數(shù)組中相加等于sum的組合""" quick_sort(arr, 0, len(arr) - 1) begin, end = 0, len(arr) - 1 while begin < end: if arr[begin] + arr[end] < sum: begin += 1 elif arr[begin] + arr[end] > sum: end -= 1 else: print('%s %s' % (arr[begin], arr[end])) begin += 1 end -= 1 if __name__ == '__main__': arr = [1, 7, 17, 2, 6, 3, 14] find_sum(arr, 20)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于Python采集爬取微信公眾號(hào)歷史數(shù)據(jù)
這篇文章主要介紹了基于Python采集爬取微信公眾號(hào)歷史數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Python K-means實(shí)現(xiàn)簡單圖像聚類的示例代碼
本文主要介紹了Python K-means實(shí)現(xiàn)簡單圖像聚類的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10詳解Python實(shí)現(xiàn)同時(shí)支持帶調(diào)用和不調(diào)用帶裝飾器
一般來說,不帶參數(shù)裝飾器,再使用時(shí)不加括號(hào),帶參數(shù)的裝飾器使用時(shí)必須加括號(hào),這篇文章主要介紹了Python實(shí)現(xiàn)同時(shí)支持帶調(diào)用和不調(diào)用帶裝飾器的相關(guān)知識(shí),需要的朋友可以參考下2023-06-06python中BackgroundScheduler和BlockingScheduler的區(qū)別
這篇文章主要介紹了python中BackgroundScheduler和BlockingScheduler的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07Django框架獲取form表單數(shù)據(jù)方式總結(jié)
這篇文章主要介紹了Django框架獲取form表單數(shù)據(jù)方式總結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04