#python #anaconda #jupyter-notebook #visual-code #html #css #javascript #http

제목step 15 search 실습자료2021-11-25 03:16
작성자

똑같이 함수 정의하고 리스트에 추가해서 파일 쓰기로 했는데

binary search에 해당하는 값만 csv 파일에 저장이 되지 않습니다,

어디가 문제인지 알려주시면 감사하겠습니다.


import time


def time_it(searchMethod, lst, value):

    t1 = time.perf_counter()

    if(searchMethod(lst, value) == -1):

        print("Error in search.")

    t2 = time.perf_counter()

    return (t2-t1)


def linear_search_for(lst, value):

    i = 0

    for i in range(len(lst)):

        if lst[i] == value:

            return i

    return -1


def linear_search_while_1(lst, value):

    i = 0

    while i != len(lst) and lst[i] != value:

        i += 1

    

    if i == len(lst):

        return -1

    else:

        return i

    

def linear_search_while_2(lst, value):

    lst.append(value)

    i = 0

    while lst[i] != value:

        i += 1

    

    lst.pop()

    

    if i == len(lst):

        return -1

    else:

        return i

    

def binary_search(lst, value):

    i = 0

    j = len(lst) - 1

    

    while i != j + 1:

        m = (i + j) // 2

        if lst[m] < value:

            i = m + 1

        else:

            j = m - 1

    

    if 0 <= i < len(lst) and lst[i] == value:

        return i

    else:

        return -1


import csv


L = list(range(10000001))


fileMatrix = []


fileMatrix.append(["Target", "Linear - for", "Linear - while", "Linear - sentinel while", "Binary"])


for_matrix = []

for_matrix.append("10")

for_matrix.append(time_it(linear_search_for, L, 10))

for_matrix.append(time_it(linear_search_for, L, 5000000))

for_matrix.append(time_it(linear_search_for, L, 10000000))


while1_matrix = []

while1_matrix.append("5000000")

while1_matrix.append(time_it(linear_search_while_1, L, 10))

while1_matrix.append(time_it(linear_search_while_1, L, 5000000))

while1_matrix.append(time_it(linear_search_while_1, L, 10000000))


while2_matrix = []

while2_matrix.append("10000000")

while2_matrix.append(time_it(linear_search_while_2, L, 10))

while2_matrix.append(time_it(linear_search_while_2, L, 5000000))

while2_matrix.append(time_it(linear_search_while_2, L, 10000000))


binary_matrix = []

binary_matrix.append("10000000")

binary_matrix.append(time_it(binary_search, L, 10))

binary_matrix.append(time_it(binary_search, L, 5000000))

binary_matrix.append(time_it(binary_search, L, 10000000))


fileMatrix.append(for_matrix)

fileMatrix.append(while1_matrix)

fileMatrix.append(while2_matrix)

fileMatrix.append(binary_matrix)


with open('Step_15_Search_timing.csv', 'w') as fileWrite:

    myWriter = csv.writer(fileWrite)

    for item in fileMatrix: 

        myWriter.writerow(item)

댓글
이전[re]오픈북 형태 Level 102021-11-25
다음[re]step 15 search 실습자료2021-11-25