이진탐색_til

Hvvany·2023년 1월 1일
0

알고리즘

목록 보기
1/12

함수를 활용한 분기

문제를 풀다가 답이면 1을 출력 답이 아니면 0을 출력하는 조건에서 조건 분기를 반복문 안에서 어떻게 해야하나 고민을 하다가 함수를 통해서 return으로 값을 출력하면 break 안걸어주고도 바로 탈출 가능하다. 그래서 while 내부에서 정답이 나오면 return하면 바로 함수가 종료가 된다. 정답이 while 내부에 없을 경우 while문 바로 아래에 return하면 while문을 모두 돌고 종료된 경우에 값을 넘길 수 있다.

https://www.acmicpc.net/problem/1920

n = int(input())
num_lst = list(map(int,input().split()))
m = int(input())
check_lst = list(map(int,input().split()))
num_lst.sort()

def binary(array, target, start, end):
    check_idx = 0

    while start <= end:
        mid = (start + end) // 2
        if array[mid] == target:
            return 1
        elif array[mid] > target:
            end = mid - 1
        else:
            start = mid + 1
    return 0

for num in check_lst:
    print(binary(num_lst, num, 0, len(num_lst)-1))
profile
Just Do It

0개의 댓글