हिंदी

Accept a list containing integers randomly. Accept any number and display the position at which the number is found is the list.

Advertisements
Advertisements

प्रश्न

Accept a list containing integers randomly. Accept any number and display the position at which the number is found is the list.

कोड लेखन
Advertisements

उत्तर

Since the list is random (unsorted), use linear search. The program displays the first position using 1-based position numbering.

def linear_search(data_list, number):
    for index, value in enumerate(data_list):
        if value == number:
            return index + 1  # Position for the user
    return -1


numbers = list(map(int, input("Enter list elements: ").split()))
search_number = int(input("Enter number to search: "))
position = linear_search(numbers, search_number)

if position == -1:
    print("Element not found")
else:
    print("Element found at position", position)

Enter list elements: 15 8 24 6 19
Enter number to search: 24
Element found at position 3
shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 5: Liner List Manipulation - EXERCISE [पृष्ठ १०४]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
अध्याय 5 Liner List Manipulation
EXERCISE | Q 9. | पृष्ठ १०४
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×