初心者向けのPythonのプログラミング問題です。入門編としてチャレンジしてください。Pythonの正答例は以下になります。
問題727
def insertion_sort_desc(lst):
for i in range(1, len(lst)):
key = lst[i]
j = i – 1
while j ≥ 0 and lst[j] < key:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
return lst
# 呼び出し例
lst = [5, 3, 8, 1]
問題728
def quick_sort_by_length(lst):
if len(lst) ≤ 1:
return lst
pivot = lst[0]
left = [x for x in lst[1:] if len(x) ≤ len(pivot)]
right = [x for x in lst[1:] if len(x) > len(pivot)]
return quick_sort_by_length(left) + [pivot] + quick_sort_by_length(right)
# 呼び出し例
lst = [“banana”, “kiwi”, “apple”, “grape”]
print(quick_sort_by_length(lst)) # 出力: [‘kiwi’, ‘apple’, ‘grape’, ‘banana’]
問題730
import time, bisect, random
def compare_search_speed(n=10000):
data = sorted(random.sample(range(n*2), n))
target = random.choice(data)
start = time.time()
_ = target in data
linear_time = time.time() – start
start = time.time()
i = bisect.bisect_left(data, target)
binary_time = time.time() – start
return linear_time, binary_time
# 呼び出し例
print(compare_search_speed())
# 出力例: (0.00123, 0.00001)



コメント