English

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

Advertisements
Advertisements

Question

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

Code Writing
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 5: Liner List Manipulation - EXERCISE [Page 104]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 5 Liner List Manipulation
EXERCISE | Q 9. | Page 104
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×