5

For example:

[1,2,3,4,5,6] -> True
[1,2,3,5,6] -> False

I guess i could do something like:

if len(set([arr[x] - arr[x - 1] for x in range(1, len(arr))])) > 1:
    print('not equally spaced')

I was wondering if there were a better way?

10
  • 1
    Better means what exactly? Commented Nov 7, 2019 at 4:23
  • 3
    Get the difference between the first two elements. Then iterate through the array, stopping if any pair has a different difference. Commented Nov 7, 2019 at 4:24
  • @StephenRauch More efficient computationally. Ideally. I think Barmar's answer is probably what i was looking for. Commented Nov 7, 2019 at 4:25
  • One thing is you don't need to construct a list. Just remove the brackets. Commented Nov 7, 2019 at 4:25
  • @learningthemachine, then use numpy. Commented Nov 7, 2019 at 4:25

6 Answers 6

8

You can just check if the difference are all the same (using numpy.diff):

import numpy as np
a = np.array([1,2,3,4,5,6])
b = np.array([1,2,3,5,6])

all(np.diff(a)==np.diff(a)[0])  # --> True
all(np.diff(b)==np.diff(b)[0])  # --> False
Sign up to request clarification or add additional context in comments.

Comments

2

Here's what i ended up doing...

def same_dist_elems(arr):
    diff = arr[1] - arr[0]
    for x in range(1, len(arr) - 1):
        if arr[x + 1] - arr[x] != diff:
            return False
    return True

Credits to Barmar but he only put in a comment not an answer

2 Comments

This is the most straightforward solution, but you should handle lists shorter than 2 as a special case. Otherwise diff = arr[1] - arr[0] will raise an IndexError.
I'm trying it with values a,b,c as follows but I am not getting an out put def same_dist_elems(a, b, c): arr = (a, b, c) diff = arr[1] - arr[0] for x in range(1, len(arr) - 1): if arr[x + 1] - arr[x] != diff: return False return True # test code same_dist_elems(2, 4, 6)
1

try this, for a list to be consecutive

  • the difference between the last item and first item plus 1 must be equal to the list length
  • length of list vs length of set must match to rule out repeated entries
  • The list need to be sorted for this to works.

code

def check_consecutive(input_list):
    input_list = sorted(input_list)
    return (input_list[-1] - input_list[0]) + 1 == len(input_list) and (len(input_list) == len(set(input_list))

check_consecutive([1,2,3,4,5,6]) # True
check_consecutive([1,2,3,5,6])   # False

like the comment mention, code above only works for spacing of 1 unit and we could omit the sort list portion if the input_list already sorted

to make it generic for any space unit, we could try code below. It first create the ideal evenly space list based on input_list space unit then diff against input_list. Code below assume input_list already sorted

def check_evenly_space(input_list):
    if len(input_list)==1:
        return False
    space = input_list[1] - input_list[0]
    if space==0:
        return False
    return list(range(input_list[0], input_list[-1] + space, space)) == input_list

check_evenly_space([1,2,3,4,5,6]) # True
check_evenly_space([1,2,3,5,6])   # False
check_evenly_space([2,4,6,8,10])  # True
check_evenly_space([2,4,6,7,10])  # False

4 Comments

"evenly spaced", but that space isn't necessarily a unit. I think you can fix this by multiplying the difference of the first two elements somewhere.
I don't think so. If the list items are not strictly adjacent, then they could have gaps that make the size comparisons not work. E.g. [1, 2, 5] would be accepted as the code can't tell the difference between it and [1, 3, 5]. And sorting the list is a bit problematic, as you need to ensure the items are in order anyway. [3, 5, 1] is not valid!
This will throw an error for lists like [3] or [5, 5, 9].
@kaya3, added fixed for that
0

A simple solution is to compare the list with a range. To save converting the range to a list, we can use zip and all. This isn't the most efficient solution possible, but it's still O(n) time and O(1) auxiliary space.

def list_is_evenly_spaced(lst):
    # special case: a list with 0, 1 or 2 elements is evenly spaced
    if len(lst) <= 2:
        return True

    first = lst[0]
    gap = lst[1] - first
    # special case: a constant list is evenly spaced
    if gap == 0:
        return all(x == first for x in lst)

    # general case: an evenly spaced list equals a range
    r = range(first, first + gap*len(lst), gap)
    return all(x == y for x,y in zip(lst, r))

Explanation of the special cases, which have to be handled separately:

  • A list of 0, 1 or 2 elements is always evenly spaced. To be unevenly spaced there have to be two different gaps, implying at least three elements.
  • A constant list is always evenly spaced, because every gap is 0. However, it's not valid to construct a range with a gap of 0.

Comments

0

You can do this easily with numpy

import numpy as np
np.diff(a) == len(a)-1

True

If speed is a concern make sure

type(a)
<type 'numpy.ndarray'>

with np.array(a)

Comments

-1

You can try this

def ContiguousElem(arr):
    ss = set() 
    for i in arr: ss.add(i)
    count = 1
    curr = arr[0] - 1
    while curr in ss:
        count += 1
        curr -= 1
    curr = arr[0] + 1

    while curr in ss: 
        count += 1
        curr += 1
    return (count == len(ss)) 
arr1 = [1,2,3,4,5,6]
arr2 = [1,2,3,5,6]
if ContiguousElem(arr1): print("Yes") 
else: print("No") 
if ContiguousElem(arr2): print("Yes") 
else: print("No") 

o/p : Yes
      No

3 Comments

Why are you casting the array to a set?
This algorithm is not straightforward, so you should explain how it works.
Here I am just trying to push the elements of 'arr[]' in a hash table/set and pick the first element and keep on increment its value by 1 till you find a value not present in the hash table. Similarly for the other elements. count of elements (obtained by this process) which are present in the hash table. If the count equals hash size print “Yes” else “No”. This way we can reduce the time complexity to O(n).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.