इस लेख में, हम सीखेंगे कि सूचियों और टुपल्स पर रैखिक खोज कैसे लागू करें।
एक रैखिक खोज पहले तत्व से खोजना शुरू करती है और सूची या टपल के अंत तक जाती है। जब भी उसे आवश्यक तत्व मिलता है, यह जाँचना बंद कर देता है।
रैखिक खोज - सूचियां और टुपल्स
सूचियों और टुपल्स पर रैखिक खोज को लागू करने के लिए नीचे दिए गए चरणों का पालन करें।
- सूची या टपल और एक तत्व को इनिशियलाइज़ करें।
- सूची में पुनरावृति करें या टपल करें और तत्व की जांच करें।
- जब भी आपको तत्व मिले तो लूप को तोड़ दें और ध्वज को चिह्नित करें।
- झंडे के आधार पर प्रिंट तत्व संदेश नहीं मिला।
उदाहरण
आइए कोड देखें।
# 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
निष्कर्ष
यदि लेख में आपके कोई प्रश्न हैं, तो उनका उल्लेख टिप्पणी अनुभाग में करें।