本文實例講述了Python查找兩個有序列表中位數的方法。分享給大家供大家參考,具體如下:
今天做到的一個機試題目,很簡單,這里簡單記錄一下:
我用的是歸并的思想,當然還可以用遞歸的方法,下面是具體實現:
#!usr/bin/env python#encoding:utf-8'''''__Author__:沂水寒城功能:找到兩個有序列表的中位數若列表總長度為奇數則直接返回中間下標的值否則返回前一個值,如長度為6則返回下標為2處的值'''import randomdef random_nums_genetor(max_value=1000, total=100): ''''' 生成隨機數 ''' num_list=[] for i in range(total): num_list.append(random.randint(1,max_value)) return num_listdef find_two_list_mid_num(num_list1,num_list2): ''''' 找到兩個有序列表的中位數 ''' length1=len(num_list1) length2=len(num_list2) total=length1+length2 if total%2==0: half=total/2-1 else: half=total/2 res_list=[] while len(num_list1) and len(num_list2): if num_list1[0]<num_list2[0]: res_list.append(num_list1.pop(0)) else: res_list.append(num_list2.pop(0)) if len(num_list1): res_list+=num_list1 elif len(num_list2): res_list+=num_list2 #print res_list print res_list[half] return res_listif __name__ == '__main__': print "武林站長站測試結果:" num_list1=[1,2,5,7,12,45,67,100] num_list2=[11,34,77,90] res_list=find_two_list_mid_num(num_list1,num_list2) print res_list[5] print '--------------------------------------------------------' num_list1=random_nums_genetor(max_value=1000, total=10) num_list2=random_nums_genetor(max_value=100, total=7) res_list=find_two_list_mid_num(num_list1, num_list2) print res_list[8]
結果如下:

(代碼摘自《Python Cookbook》)
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答