코드잇 Divide and Conquer 알고리즘 문제
start와 end를 사용한 반값을 활용
def consecutive_sum(start, end):
# 코드를 작성하세요
# base cass
if start == end:
return start
# recursive case
else:
half = (start + end) // 2
return consecutive_sum(start, half) + consecutive_sum(half +1, end)
# 테스트
print(consecutive_sum(1, 10))
print(consecutive_sum(1, 100))
print(consecutive_sum(1, 253))
print(consecutive_sum(1, 388))
def merge(list1, list2):
# 코드를 작성하세요.
# # divide
# if 1 < len(list1):
# half = len(list1) // 2
# merge(list1[:half],list2[:half])
# merge(list1[half:],list2[half:])
# # conquer
# elif len(list1) < 2 and len(list2) < 2:
return sorting(list1, list2)
def sorting(list1, list2):
result = []
for i in range(len(list1)+len(list2)):
if len(list1) == 0:
small = list2.pop(0)
result.append(small)
elif len(list2) == 0:
small = list1.pop(0)
result.append(small)
elif len(list2) == 0:
result.append(list1)
break
elif list1[0] < list2[0]:
small = list1.pop(0)
result.append(small)
else:
small = list2.pop(0)
result.append(small)
return result
# 테스트
print(merge([1],[]))
print(merge([],[1]))
print(merge([2],[1]))
print(merge([1, 2, 3, 4],[5, 6, 7, 8]))
print(merge([5, 6, 7, 8],[1, 2, 3, 4]))
print(merge([4, 7, 8, 9],[1, 3, 6, 10]))
구상
구현 - 실패
# def merge(list1, list2):
# # 이전 과제에서 작성한 코드를 붙여 넣으세요!
# result = []
# for i in range(len(list1)+len(list2)):
# if len(list1) == 0:
# small = list2.pop(0)
# result.append(small)
# elif len(list2) == 0:
# small = list1.pop(0)
# result.append(small)
# elif len(list2) == 0:
# result.append(list1)
# break
# elif list1[0] < list2[0]:
# small = list1.pop(0)
# result.append(small)
# else:
# small = list2.pop(0)
# result.append(small)
# return result
# 합병 정렬
def merge_sort(my_list):
# 코드를 입력하세요.
if len(my_list) < 2:
return my_list
left = my_list[:len(my_list)//2]
right = my_list[len(my_list)//2:]
return merge(merge_sort(left), merge_sort(right))📌
# # 테스트
# print(merge_sort([1, 3, 5, 7, 9, 11, 13, 11]))
# print(merge_sort([28, 13, 9, 30, 1, 48, 5, 7, 15]))
# print(merge_sort([2, 5, 6, 7, 1, 2, 4, 7, 10, 11, 4, 15, 13, 1, 6, 4]))
return merge(merge_sort(left), merge_sort(right))📌