Skip to content

Instantly share code, notes, and snippets.

@DSLituiev
Last active September 11, 2019 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DSLituiev/1237b479058b4117da366b26dd6f2efd to your computer and use it in GitHub Desktop.
Save DSLituiev/1237b479058b4117da366b26dd6f2efd to your computer and use it in GitHub Desktop.
find index of first non-negative value in a sorted list
def split(x):
"""return the index of the first non-negative value in a sorted list:
legend for comments:
"-" stands for negative
"+" stands for non-negative
"""
# check for corner cases:
if len(x)==0:
return 0
elif len(x)==1:
return 1
ind = len(x)//2
if (x[ind]>=0) and ((x[ind-1] < 0)):
# .......-|+.......
return ind
elif (x[ind]>=0) and ((x[ind-1] >= 0)):
# ......+|+......
# descend into the left side
return split(x[:ind])
elif x[ind]<0:
# .....-|-.......
# descend into the right
return ind + split(x[ind:])
# corner case: only non-negatives
seq = list(range(0,10))
ind = split(seq)
print(ind) # -> 0
# corner case: only negatives
seq = list(range(-10,0))
ind = split(seq)
print(ind) . # -> 10
# regular cases
import random
for _ in range(20):
seq = sorted([random.randint(-100, 100) for _ in range(10)])
ind = split(seq)
assert (seq[ind-1]<0) and(seq[ind]>=0)
print(seq[ind-1],'|', seq[ind])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment