1st with operations

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.1 kB
3
Indexable
def linear_search(arr, target):
    operations = 0
    for num in arr:
        operations += 1
        if num == target:
            return True, operations
    return False, operations

try:
    n = int(input("Enter the number of elements in the list: "))
    if n < 1 or n > 50:
        print("Please enter a valid number of elements between 1 and 50.")
    else:
        num_list = []
        for i in range(n):
            num = int(input(f"Enter number {i + 1} (between 1 and 50): "))
            if 1 <= num <= 50:
                num_list.append(num)
            else:
                print("Please enter a number between 1 and 50.")

        search_num = int(input("Enter a number to search in the list: "))

        found, num_operations = linear_search(num_list, search_num)

        if found:
            print(f"{search_num} is present in the list with {num_operations} operations.")
        else:
            print(f"{search_num} is not present in the list with {num_operations} operations.")
except ValueError:
    print("Invalid input. Please enter a valid number.")