Home > Back-end >  Binary search through string tuple in list
Binary search through string tuple in list

Time:11-12

I'm trying to do a binary search through a list of tuples, when I give a inputq = "BB", it is not show a correct search.

This is my data:

alldtata = [('BA', 'Bosnia and Herzegovina', 44.0, 18.0), ('BB', 'Barbados', 13.17, -59.53), ('BD', 'Bangladesh', 24.0, 90.0), ('BE', 'Belgium', 50.83, 4.0), ('BF', 'Burkina Faso', 13.0, -2.0), ('BG', 'Bulgaria', 43.0, 25.0), ('BH', 'Bahrain', 26.0, 50.55), ('BJ', 'Benin', 9.5, 2.25), ('BM', 'Bermuda', 32.33, -64.75), ('BN', 'Brunei Darussalam', 4.5, 114.67)]

This my code:

def binarySearch(arr, x):
    l = 0
    r = len(arr)-1
    while (l <= r):
        m = l   ((r - l) // 2)
        res = (x == arr[m])
        if (res == 0):
            return m - 1
        if (res > 0):
            l = m   1
        else:
            r = m - 1
 
    return -1

inputq = "BB"
showall = binarySearch(alldtata, inputq)
for indexcodename, value in enumerate(alldtata):
    if indexcodename == showall:
        print(value)

when I give inputq = "BB" the output it always show like this: ('BF', 'Burkina Faso', 13.0, -2.0)

I would like to show my output like this when I give inputq = "BB"

('BB', 'Barbados', 13.17, -59.53) how to do that?

CodePudding user response:

I found two main problems with your algorithm. First, as @gog points out, you are calculating res as a boolean, but then are comparing it with integers. The other thing is that you are comparing the term arr[m] to the target, as though that term refers to the equivalent value in the data structure. It does not. Rather, it refers to the entire tuple. What you want instead is arr[m][0].

Fixing those two issues, and maybe a few small issues, here's a new version of your code that seems to correctly find any value in the array:

def binarySearch(arr, x):
    l = 0
    r = len(arr)-1
    while l <= r:
        m = l   ((r - l) // 2)
        mm = arr[m][0]
        if x == mm:
            return m
        if x > mm:
            l = m   1
        else:
            r = m - 1
    return -1

Result (when the original function is replaced with this new version in the original code):

('BB', 'Barbados', 13.17, -59.53)
  • Related