how to optimize this code and make it faster on python

Question:

determine whether all values of a certain range are used in the array and at the same time there are no values in the array that will not be in the range. For example, the range is [1,5], and the array is [1,2,3,4,5] – everything is correct. Or the range [1,5], and the array [1,2,1,2,3,3,4,5] – everything is also true.
the range is [1,5], and the array [0,2,2,3,3,4,5] is already incorrect since there is no 0 in the range, and there is also a 1 missing in the array

I did this, but it’s slow with big values and terrible:

def func(segment, arr):
    segment_arr = []
    for i in range(segment[0], segment[1] + 1):
        segment_arr.append(i)
    arr_corr = True
    if min(arr) != min(segment_arr) or max(arr) != max(segment_arr):
        arr_corr = False
    else:
        for i in range(len(arr)):
            if arr[i] in segment_arr:
                for a in range(len(segment_arr)):
                    if segment_arr[a] in arr:
                        continue
                    else:
                        arr_corr = False
            else:
                arr_corr = False
    return arr_corr 
Asked By: ssssilentdark

||

Answers:

To test if every member of a list/array/range x is in another list/array y:

all(e in y for e in x)

to test if only members of a list/array/range x are in another list/array y:

all(e in x for e in y)

The speed of these operations depends on the container type. all short circuits, so it will be faster when the test fails. in is very fast on set but can be slow on lists. Creation of set is slow and can eliminate the gains from the speed of doing in on a set. If you are working with numpy arrays, it will be faster to use numpy’s intersect.

This should do what you’re asking. If it is too slow, you will need to optimize the types. At that point, you will probably need to edit the question to give some clear examples of when it is too slow and what your constraints are:

def func(segment, arr):
    return all(e in segment for e in arr) and all(e in arr for e in segment)
Answered By: philosofool
def func(segment, arr):
    return set(list(range(segment[0], segment[1]+1))) == set(arr)
Answered By: Alex
  1. Build a set from allowed values
  2. If the resulting set has "full" length, all is correct.
left, right = [1, 5]
values = [0, 2, 3, 4, 5]
values_are_correct = (
    len({i for i in values if left <= i <= right}) == (right - left) + 1
)
Answered By: westandskif
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.