I have a list of values and I need to, given any arbitrary starting index, find the closest value which is non zero, if the value at the starting index is zero...
Here is what I have:
def getNearestNonZero(start_index): mylist = [4,2,6,7,3,0,0,9,4,2,5,8,1,7] val = mylist[start_index] if val == 0: loop_length = 0 after = mylist[start_index+1:] before = mylist[:start_index] before = before[::-1] print(before, after) if len(before) >= len(after): loop_length = len(before) else: loop_length = len(after) for i in range(loop_length): if i < len(before): before_val = before[i] if i < len(after): after_val = after[i] if before_val > 0: return before_val if after_val > 0: return after_val return val result = getNearestNonZero(6) print(result) result = getNearestNonZero(5) print(result)
[0, 3, 7, 6, 2, 4] [9, 4, 2, 5, 8, 1, 7]
[3, 7, 6, 2, 4] [0, 9, 4, 2, 5, 8, 1, 7]
What I do, is I first check to see if the value at the
start_index is > 0. If it is, great, return it. If however, the value is zero, we need to find the closest non-zero, with a preference for before, rather than after...
To do this, I split
mylist into two separate lists,
after. If my start index is 6,
before will now look like:
[4,2,6,7,3,0] and after will look like:
Since I need the closest value to the
start_index, I reverse my
before = before[::-1]
I then get the length of the longest of the two (
I then loop and check the value at each index of the two lists. The first one to have a value > 0 is returned and my work is done.
However, this feels very clunky and as if it can be done in a cleaner way.
Does anyone have any recommendations? What is the faster/cleaner/pythonic way for finding the nearest non-zero value in a list, given a starting index?