0

I cannot find a solution to find groups of strictly increasing "float values" within a list. All examples I find online are all group by "integers" type values. A simple example of what I am looking for is code that picks up the float value sequence as well...see my list below for clarity:

l = [8, 9, 10, -1.2, -1.1 ,-1.0, -10, -11, -12, 7, 8, 1.2, 2.3, 3.4]

the code below returns only the integer numbers and simply ignores the floats. If I would use the "round" function to change the list into integers, it would defeat the whole purpose of the effort...

What I would like to achieve is an output of strictly increasing "float values" from the list above returning the output values of: [[8, 9, 10],[-1.2,-1.1,-1.0] , [7, 8], [1.2, 2.3, 3.4]]

Code to explain the problem best:

def groupSequence(x): 
    it = iter(x) 
    prev, res = next(it), [] 
  
    while prev is not None: 
        start = next(it, None) 
  
        if prev + 1 == start: 
            res.append(prev) 
        elif res: 
            yield list(res + [prev]) 
            res = [] 
        prev = start 

l = [8, 9, 10, -1.2, -1.1 ,-1.0, -10, -11, -12, 7, 8, 1.2, 2.3, 3.4]
print(list(groupSequence(l)))

#current output: [[8, 9, 10], [7, 8]]

#desired output [[8, 9, 10],[-1.2,-1.1,-1.0] , [7, 8], [1.2, 2.3, 3.4]]

Any help would be much appreciated.

  • 2
    Does this answer your question? [Finding groups of increasing numbers in a list](https://stackoverflow.com/questions/33402355/finding-groups-of-increasing-numbers-in-a-list) – python_user Jan 05 '21 at 08:49
  • 1
    Shouldn't the third element of your desired output be `[-12, 7, 8]`? – Chris Jan 05 '21 at 08:53
  • Gees that's a quick response...Yes, you are correct. My bad.. – G. Rohlandt Jan 05 '21 at 08:59
  • answer in link "Finding groups of increasing numbers in a list" are all integers and not floats... does not answer my question. – G. Rohlandt Jan 05 '21 at 09:01
  • Why are you doing `prev + 1 == start`? the floating series does not match this assertion, so it's pretty normal they are ignored – olinox14 Jan 05 '21 at 09:02
  • reply in 1: "Shouldn't the third element of your desired output be [-12, 7, 8]" is correct. My bad. Response should also include [-12,7,8] in the desired output as they are following sequence for increasing numbers... – G. Rohlandt Jan 05 '21 at 09:03
  • response in " Why are you doing prev + 1 == start? the floating series does not match this assertion, so it's pretty normal they are ignored – olinox14 1 min ago".... This is an example code. Was struggling to explain the issue. The float numbers can vary substantially so need to cater for that as well... – G. Rohlandt Jan 05 '21 at 09:05

1 Answers1

0

The problem is in this line:

if prev + 1 == start:

The floats in your sequence doesn't increase by one: -1.2 + 1 <> -1.1

if start and start > prev:
obeq
  • 675
  • 1
  • 4
  • 14