이 기사에서는 목록과 튜플에 선형 검색을 적용하는 방법을 배울 것입니다.
선형 검색은 첫 번째 요소에서 검색을 시작하여 목록 또는 튜플 끝까지 이동합니다. 필요한 요소를 찾을 때마다 확인을 중지합니다.
선형 검색 - 목록 및 튜플
목록 및 튜플에 대한 선형 검색을 구현하려면 아래 단계를 따르세요.
- 목록 또는 튜플과 요소를 초기화합니다.
- 목록 또는 튜플을 반복하고 요소를 확인합니다.
- 요소를 찾고 플래그를 표시할 때마다 루프를 중단합니다.
- 플래그를 기반으로 메시지를 찾을 수 없는 인쇄 요소입니다.
예시
코드를 봅시다.
# function for linear search
def linear_search(iterable, element):
# flag for marking
is_found = False
# iterating over the iterable
for i in range(len(iterable)):
# checking the element
if iterable[i] == element:
# marking the flag and returning respective message
is_found = True
return f"{element} found"
# checking the existence of element
if not is_found:
# returning not found message
return f"{element} not found"
# initializing the list
numbers_list = [1, 2, 3, 4, 5, 6]
numbers_tuple = (1, 2, 3, 4, 5, 6)
print("List:", linear_search(numbers_list, 3))
print("List:", linear_search(numbers_list, 7))
print("Tuple:", linear_search(numbers_tuple, 3))
print("Tuple:", linear_search(numbers_tuple, 7)) 위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
출력
List: 3 found List: 7 not found Tuple: 3 found Tuple: 7 not found
결론
기사에서 궁금한 점이 있으면 댓글 섹션에 언급하세요.