0

I've read this question

But my question is a little different:

For example:

[0.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 5.0, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10.0]

should gave me:

[[0.0], [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9], [5.0], [9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10.0]]

All the types of them is float.The difference of each element of sub list should smaller than 0.1.

I try to solve it without using third party module.(Not homework, just a practice for python)

What I have tried: too much code with itertools.groupby(Couldn't solve it).One of my attempt:

import itertools

lst = [0.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 5.0, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10]

res = []
for _, item in itertools.groupby(enumerate(lst), key=lambda index_num: index_num[0]-index_num[1]):
    print(list(item)) # Not expected. The solution I mentioned didn't work.

I want a neat, pythonic way to solve it.Any tricks are welcomed, I just want to learn more skills.:)

Kevin Mayo
  • 1,089
  • 6
  • 19
  • Does this answer your question? [Group consecutive integers and tolerate gaps of 1](https://stackoverflow.com/questions/21142231/group-consecutive-integers-and-tolerate-gaps-of-1) , in @jonrsharpe solution change `if next_ > current + tol + 1:` to `if next_ > current + tol + 0.1:` you will get your answer – sahasrara62 Dec 02 '20 at 13:49
  • @sahasrara62 Thanks, What's the time complexity of his solution? Is it `O(n)`? – Kevin Mayo Dec 02 '20 at 13:57

0 Answers0