Given a Python list consists of plus or minus numbers, we need to sort that list then find the maximum gap between the successive numbers in that list regarding of its sign.

For example,

maxGap ({-7,-42,-809,-14,-12}) ==> return (767)

Explanation:

`The Maximum Gap after sorting the array is 767, The difference between | -809- (-42) | = 767.`
```def max_gap(numbers):

numbers.sort()
gap = []

while(len(numbers) > 1):
first = numbers.pop(0)
second = numbers
gap.append(abs(second-first))

return max(gap)
```
1. Sort the list in ascending order.
2. Create a full gap list in the while loop.
3. Return the maximum different.

The above question is from Codewars, which is the best website for you to train your Python and other programming skill.

## 5 Comments

1. Test says:

def max_gap(numbers):
import numpy as np
numbers.sort()
return max(np.diff(numbers))

2. IkeE says:

Or you could be more Pythonic:

def max_gap(numbers):
numbers.sort()
return max([a-b for a,b in zip(numbers[1:],numbers)])

3. Terry Reedy says:

Bad solution. Once numbers are sorted (O(n*logn)), finding the max gap should be O(n) but popping from the front of the list makes the function O(n*n) and unidiomatic. Also, abs is not needed as differences are already positive.

def max_gap(numbers):
if len(numbers) < 2:
raise ValueError("Need at least 2 numbers to have a gap")
numbers.sort()
num = iter(numbers)
gap = []
first = next(num)
for second in num:
gap.append(second-first)
first = second
return max(gap)

print(max_gap([-7,-42,-809,-14,-12]))

1. IslandTropicalMen says:

ok

4. Messager Jean-Pierre says:

Another approach using iterators in a more Python3 style (in my opinion, it is quite LISPish as well 🙂 ) :

def my_max_gap(numbers):
numbers = sorted(numbers)
return max(
( second – first for first,second in
zip(numbers,islice(numbers,1,None) ) ) )