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.
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:
JavaScript
x
20
20
1
z=min(arr)
2
if (z<x):
3
curr=arr[0]
4
glob=z
5
for i in range(0,n):
6
curr=arr[i]
7
if glob>curr:
8
if curr<x:
9
glob=curr
10
"""elif glob >curr:
11
continue"""
12
if(glob<curr):
13
if curr<x:
14
glob=curr
15
else:
16
continue
17
return glob
18
else:
19
return -1
20
Test case I am not able to pass:
Advertisement
Answer
You can try something like that:
JavaScript
1
11
11
1
arr = [4, 67, 13, 12, 15]
2
X = 16
3
4
smaller = -1
5
6
for i in arr:
7
if 0 < X - i < X - smaller:
8
smaller = i
9
10
print(smaller) # or return if it's a function
11
Output:
JavaScript
1
2
1
15
2
And for arr = [1, 2, 3, 4, 5]
and X = 1
it prints -1
.