B.Mr.W. - 11 months ago 62

Python Question

I am wondering if there is a function in Python already written for the goal that I describe later. If not, what would be the easiest way to implement. My code is attached.

Say I have a range from 1 to 999999999. Given a list of numbers like this:

`[9, 44, 99]`

It would return

`[(1,9), (10,44), (45,99), (100, 999999999)]`

If the number which are the limits are included in the input numbers, it should handle that also.

Say input is

`[1, 9, 44, 999999999]`

The return should be:

`[(1,9), (10,44), (45, 999999999)]`

I could write a for loop comparing with a few conditional statement but wondering if there is a more 'smart way'.

Some data massage that might be helpful:

`points = [1, 9, 44, 99]`

points = sorted(list(set(points + [1, 999999999])))

FINAL CREDITS GIVEN TO alecxe, thanks for your inspiring list comprehension solution

`l = sorted(list(set(points + [1, 999999999])))`

[(l[i] + int(i != 0), l[i + 1]) for i in xrange(len(l) - 1)]

You can put all that in one line but I think that is unnessary.

Answer Source

Not sure this approach is the best one:

```
>>> l = [1, 9, 44, 999999999]
>>> [(l[i] + int(i != 0), l[i + 1]) for i in xrange(len(l) - 1)]
[(1, 9), (10, 44), (45, 999999999)]
```

If you are on python 3, replace `xrange`

with `range`

.

Note, that for your first example to work, you'll need to prepend and append your boundaries:

```
>>> l = [9, 44, 109]
>>> low, high = 1, 999999999
>>> l = [low] + l + [high]
>>> [(l[i] + int(i != 0), l[i + 1]) for i in xrange(len(l) - 1)]
[(1, 9), (10, 44), (45, 109), (110, 999999999)]
```