Skip to content
Advertisement

Finding immediate smaller than X

So, we have been provided with a list and a value X. In the given list we have to find the immediate smaller value than X. Here is my code. Where am I doing it wrong? I am also attaching the provided test cases and the test case which I am not able to pass.

Sample input and output

I was able to pass the given sample test case but not the hidden one. Whenever I modify my code, it leaves one or another test case. I can see the solution but I want to correct my code.

And here is my code:

    z=min(arr)
    if (z<x):
        curr=arr[0]
        glob=z
        for i in range(0,n):
            curr=arr[i]
            if glob>curr:
                if curr<x:
                    glob=curr
                """elif glob >curr:
                    continue"""
            if(glob<curr):
                if curr<x:
                    glob=curr
            else:
                continue
        return glob  
    else:
        return -1

Test case I am not able to pass:

Hidden test case

Advertisement

Answer

You can try something like that:

arr = [4, 67, 13, 12, 15]
X = 16

smaller = -1

for i in arr:
    if 0 < X - i < X - smaller:
        smaller = i

print(smaller)  # or return if it's a function

Output:

15

And for arr = [1, 2, 3, 4, 5] and X = 1 it prints -1.

Advertisement