PythonプログラミングノックDay230 初心者向けソート・探索 #プログラミング #python #初心者

入門

初心者向けのPythonのプログラミング問題です。入門編としてチャレンジしてください。Pythonの正答例は以下になります。

問題688
def find_first_greater_equal(lst, value):
for x in lst:
if x >= value:
return x
return None
#>は半角記号に変換

# 呼び出し例
lst = [1, 3, 5, 7, 9]
print(find_first_greater_equal(lst, 6)) # 出力: 7

問題689
def find_less_than(lst, value):
return [x for x in lst if x < value]
#<は半角記号に変換

# 呼び出し例
lst = [2, 5, 1, 9, 3]
print(find_less_than(lst, 4)) # 出力: [2, 1, 3]

問題690
import bisect

def binary_search(lst, value):
lst_sorted = sorted(lst)
index = bisect.bisect_left(lst_sorted, value)
if index < len(lst_sorted) and lst_sorted[index] == value:
return index
else:
return -1
#<は半角記号に変換

# 呼び出し例
lst = [8, 3, 6, 1, 4]
print(binary_search(lst, 6)) # 出力: 3(昇順にしたときの位置)

コメント

タイトルとURLをコピーしました