pythonalgorithmlinear-search

Troubleshooting an algorithim in Python


In my Python code I'm trying to be able to have the user type in one of the operating systems from the printed list and then have an algorithm spit out it's index within the specified tuple. However, even when I type in an operating system from the list, it returns the error message I made:

"please select an option from the list next time."

What can I do to fix this?

Here's the code below:

print("""Operating systems available: 

Windows 10
Linux Mint
Mac OS 11
Android Oreo
Android Pie
Android 11
iOS 14
""")

desired_string = input("From the above list, what operating system would you like to use?: ")

my_tuple = ["Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"]

def linear_search(desired_string, my_tuple):
    for each_item_index in range(len(my_tuple)):
        if desired_string == my_tuple[each_item_index]:
            return each_item_index
    return -1


if desired_string != ("Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"):
    print("please select an option from the list next time.")
    quit()

else:
    search = linear_search(desired_string, my_tuple)

    print(search) 

Solution

  • Insted of using this,

    if desired_string != ("Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"):
        print("please select an option from the list next time.")
        quit()
    

    != It checks the value as well as datatype. in the above case is (string != tuple) It's True

    Use this,

    if desired_string not in ("Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"):
        print("please select an option from the list next time.")
        quit()
    

    in keyword is used to check wheather the element in the list/tuple is present if its present it return True otherwise False.

    not in it is inverse of in if the element is present it return False. If the element is not present in the tuple/list it returns True