I am trying to, as the title suggests, loop through a list of data to create pairs and continue doing so until no more pairs can be made. For context, I am working with floats, and want to go through all elements in the list, and then compare them to every other element to see if they are within 0.03
above or below the current item.
If they are, then I am trying to create a tuple within the list of them which is made of a high and a low. I then want to continue looping through the entire list until all "ranges" that group together are grouped.
I've tried to frankenstein some code together, using what python knowledge I have and by breaking this up into smaller issues that can be individually looked at but haven't got anything to work so far. The nearest I have come is the incomplete code below:
s = []
t = ()
for item in items:
for v in items:
if v < (item + 0.03) and v > (item - 0.03):
t = (item, v)
s.append(t)
Though I am not sure where to insert the loop, or how to condition it and I am not yet replacing matching items with a tuple, this is just the rough start.
What the outcome should be is something like this (I'm not picky on the specifics as long as I can create all the groups):
Initial List: 1.05, 1.07, 1.18, 1.19, 1.22, 1.26, 1.30, 1.32
On the first pass this creates:
[(1.07, 1.05), (1.19, 1.18), 1.22, 1.26, (1.30, 1.32)]
At this point paired numbers are in tuples where the first position is the high of the range, the second is the low of the range.
Next Pass (and last for this short example):
[(1.07, 1.05), (1.22, 1.18), 1.22, 1.26, (1.30, 1.32)]
Note that the previous high for the second tuple was replaced by the new high that fell within that range of 0.03
, 1.22
This is just how I imagine it unfolding, but as long as I achieve that end result of finding all the ranges of pairs then I'll be successful.
To explain the why: I am looking for "zones" on a graph (or rather the data points of a line graph). I define similar points as 0.03 away from each other, and when it is done I'll be able to draw horizontal lines on the graph to show zones of activity. The zone doesn't have to have a set height, it can be large or small, as long as every point is 0.03 distance from the nearest neighbors. Also, if we had (1.01, 1.03) and (1.05, 1.08) the list would become (1.01, 1.08) so I know that this range or group goes from 1.01 to 1.08. (low and high respectively). 1.03 and 1.05 no longer matter as they are within that zone.