2

if i have a tuple set of numbers:

locSet = [(62.5, 121.0), (62.50000762939453, 121.00001525878906), (63.0, 121.0),(63.000003814697266, 121.00001525878906), (144.0, 41.5)]

I want to group them with a tolerance range of +/- 3.

aFunc(locSet)

which returns

[(62.5, 121.0), (144.0, 41.5)]

I have seen Identify groups of continuous numbers in a list but that is for continous integers.

Community
  • 1
  • 1
lapolonio
  • 1,107
  • 2
  • 14
  • 24
  • 1
    There can be multiple solutions. How will you group `[(10, 20), (12, 20), (14, 20)]` ? – wim Mar 20 '15 at 06:12

1 Answers1

0

If I have understood well, you are searching the tuples whose values differs in an absolute amount that is in the tolerance range: [0, 1, 2, 3]

Assuming this, my solution returns a list of lists, where every internal list contains tuples that satisfy the condition.

def aFunc(locSet):
  # Sort the list.
  locSet = sorted(locSet,key=lambda x: x[0]+x[1])

  toleranceRange = 3
  resultLst = []
  for i in range(len(locSet)):
      sum1 = locSet[i][0] + locSet[i][1]
      tempLst = [locSet[i]]
      for j in range(i+1,len(locSet)): 
          sum2 = locSet[j][0] + locSet[j][1]
          if (abs(sum1-sum2) in range(toleranceRange+1)):
              tempLst.append(locSet[j])

      if (len(tempLst) > 1):
          for lst in resultLst:
              if (list(set(tempLst) - set(lst)) == []):
                  # This solution is part of a previous solution.
                  # Doesn't include it.
                  break
          else:
              # Valid solution.
              resultLst.append(tempLst)

  return resultLst

Here two use examples:

locSet1 = [(62.5, 121.0), (62.50000762939453, 121.00001525878906), (63.0, 121.0),(63.000003814697266, 121.00001525878906), (144.0, 41.5)]
locSet2 = [(10, 20), (12, 20), (13, 20), (14, 20)]

print aFunc(locSet1)
[[(62.5, 121.0), (144.0, 41.5)]]

print aFunc(locSet2)
[[(10, 20), (12, 20), (13, 20)], [(12, 20), (13, 20), (14, 20)]]

I hope to have been of help.