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

初心者

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

問題697
def first_greater_than(lst, value):
lst_sorted = sorted(lst)
for x in lst_sorted:
if x > value:
return x
return None

# 呼び出し例
lst = [8, 3, 6, 1, 4]
print(first_greater_than(lst, 4)) # 出力: 6

問題698
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
return -1

# 呼び出し例
lst = [10, 2, 8, 5]
print(binary_search(lst, 8)) # 出力: 2

問題699
def find_words_containing(lst, char):
lst_sorted = sorted(lst)
return [w for w in lst_sorted if char in w]

# 呼び出し例
lst = [“apple”, “banana”, “cherry”, “avocado”]
print(find_words_containing(lst, “a”)) # 出力: [‘apple’,’avocado’,’banana’]

コメント

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