アルゴリズム構築 トップダウン方式
オライリーの[初めてのコンピュータサイエンス]より、メモとして
1行に1命令を書き出す
#リストLに含まれるもっとも小さな2つの値の添字をタプルで返す def find_two_smallest(L): #Lの最小値の添字を探す #リストからその要素を削除 #リストの新しい最小値の添字を探す #2個の添字を返す
コードを書く
def find_two_smallest(L): #Lの最小値の添字を探す smallest_index = min(L) min1 = L.index(smallest_index) #リストからその要素を削除 L.remove(smallest_index) #リストの新しい最小値の添字を探す next_smallest_index = min(L) min2 = L.index(next_smallest_index) #2個の添字を返す return(min1,min2)
不足要件があれば追加する
def find_two_smallest(L): #Lの最小値の添字を探す smallest_index = min(L) min1 = L.index(smallest_index) #リストからその要素を削除 L.remove(smallest_index) #リストの新しい最小値の添字を探す next_smallest_index = min(L) min2 = L.index(next_smallest_index) #最初に削除したものを戻す(追加) L.insert(min1,smallest_index) #戻した最初のIndexが2番目より前であれば+1して正しいIndexをセット(追加) if min1 <= min2: min2 += 1 #2個の添字を返す return(min1,min2)
全体はこんな感じ
# -*- coding: utf-8 -*- #リストLに含まれるもっとも小さな2つの値の添字をタプルで返す def find_two_smallest(L): #Lの最小値の添字を探す smallest_index = min(L) min1 = L.index(smallest_index) #リストからその要素を削除 L.remove(smallest_index) #リストの新しい最小値の添字を探す next_smallest_index = min(L) min2 = L.index(next_smallest_index) #最初に削除したものを戻す(追加) L.insert(min1,smallest_index) #戻した最初のIndexが2番目より前であれば+1して正しいIndexをセット(追加) if min1 <= min2: min2 += 1 #2個の添字を返す return(min1,min2) arr = [1,6,2,3] print (find_two_smallest(arr))