Python Program to check if array contains all the elements in the range

In this article, we will learn how to check if a given array contains all the elements in the given range in Python.

Example

arr[] = {2, 6, 7, 8, 9, 10, 12, 14}
range = {5, 10}
Output: True

Method 1: Using Nested Loops

1. For every element from range from the lower limit to the upper limit check whether it is present in the given array.

2. If not present return False.

3. Else return True.

def all_elements(arr, l, u):
    for i in range(l,u+1):
        if i not in arr:
            return False
    return True


arr = [2, 6, 7, 8, 9, 10, 12, 14]
l = 6
u = 10
if (all_elements(arr, l, u)):
    print("The array contains all the elements in range")
else:
    print("The array does not contains all the elements in array")
    
arr1 = [3, 19, 16, 17, 18, 20, 14]
l1 = 16
u1 = 22
if (all_elements(arr1, l1, u1)):
    print("The array contains all the elements in the range")
else:
    print("The array does not contain all the elements in the array")

Output

The array contains all the elements in the range
The array does not contain all the elements in the array

Method 2: Using all()

1. all() method return True all the elements in the iterable are true else, return False.

def all_elements(arr, l, u):
    result = all(i>= l and i<u for i in arr)
    return result


arr = [2, 6, 7, 8, 9, 10, 12, 14]
l = 6
u = 10
print ("The given array is: ", str(arr))
if (all_elements(arr, l, u)):
    print("The array contains all the elements in range")
else:
    print("The array does not contains all the elements in array")
    
arr1 = [3, 19, 16, 17, 18, 20, 14]
l1 = 16
u1 = 22
print ("The given array is: ", str(arr1))
if (all_elements(arr1, l1, u1)):
    print("The array contains all the elements in range")
else:
    print("The array does not contains all the elements in array")

Output

The given array is: [2, 6, 7, 8, 10, 12, 14]
The array does not contain all the elements in the array
The given array is: [3, 19, 16, 18, 20, 14]
The array does not contain all the elements in the array

Leave a Reply

Your email address will not be published.