Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why is v 3 when it should be 1

+13 votes

1 Answer

0 votes
answered Jan 26 by Peter Minarik (55,760 points)
edited Jan 27 by Peter Minarik

The direct answer

The above code doesn't do what you think ((3 - 1) // 2) it does. This is how it is actually executed:
v = len(c) - (1 // 2)

i.e. operator precedence says integral division comes firest, then subtractions: 3 - (1 // 2) = 3 - 0 = 3

Problems in your code

I looked at your code a bit longer. :)

Your function has many bugs (e.g. disregarding operator precedence, infinite loops for not checking for correct exit conditions) and even your binary search algorithm seems to be wrong (checking for left side only, not checking for the right side).

I'd suggest first familiarizing yourself with the correct algorithm of binary search, then trying to implement it. Then ask for a review.

There's not much point in fixing all the mistakes in your original function when probably the whole function should be rewritten anyway.

A good time though: to be able to handle tuples () and arrays [] as well, do not compare against an empty tuple or array, rather check the length if it is not 0. E.g.:

while (len(c) > 0 and c[v] != e):

Good luck!


I'll share below whatever I've fixed so far, so now your code runs, but it returns the wrong result, as the binary search algorithm is not implemented correctly

def bsearch(c, e):
    v = len(c) // 2
    #print(f"v = {v}")
    #print(f"c = {c}")
    while (len(c) > 0 and c[v] != e):
        #print(f"v = {v}")
        while (e < c[v] and not c[v] == e and not v == 0):
            v //= 2
        if (not c[v] == e):
            c = c[:v]
            v = len(c) // 2
        #print(f"v in next iteration: {v}")
        #print(f"c in next iteration: {c}")
    if (len(c) > 0 and c[v] == e):
        return True
    return False    

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.