Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between “`lo == 0, hi == len(cards) – 1“` and “`lo, hi = 0, len(cards) – 1“`

I am currently practicing binary search and I’m having trouble understanding the difference in syntax between lo == 0, hi == len(cards) - 1 and lo, hi = 0, len(cards) - 1. The code works with the second method but not with the first one. Any help would be appreciated. Thank you.

The code is as follows:

def binary_search(cards, query):
    # lo == 0, hi == len(cards) - 1
    lo, hi = 0, len(cards) - 1
    while lo <= hi:
        mid = (lo+hi) // 2
        result = locate_card(cards, query, mid)
        mid_card = cards[mid]
        print('lo: ', lo, 'hi: ', hi)
        print('mid: ', mid)
        print('mid_card: ', mid_card)
        print('result: ', result)
        print('\n')
        if result == 'found':
            return mid
        elif result == 'left':
            hi = mid - 1
        else:
            lo = mid + 1
    return -1

def locate_card(cards, query, mid):
    if cards[mid] == query:
        if mid > 0 and cards[mid-1] == query:
            return 'left'
        else:
            return 'found'
    elif cards[mid] < query:
        return 'left'
    else:
        return 'right'
    
    return binary_search(cards, query)

if __name__ == '__main__':
    cards = [13, 11, 10, 7, 4, 3, 1, 0]
    query = 1
    print(binary_search(cards, query))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A double equal-sign (==) is the operator to compare two object to see if they are equal. lo == 0, hi == len(cards) - 1 will compare lo to 0 and hi to len(cards)-1.

lo, hi = 0, len(cards) - 1 is the same as writeing

lo = 0
hi = len(cards) - 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading