
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Check if an array contains all elements of a given range in Python
Suppose we have an array called nums. We also have two numbers x and y defining a range [x, y]. We have to check whether the array contains all elements in the given range or not.
So, if the input is like nums = [5,8,9,6,3,2,4] x = 2 y = 6, then the output will be true as there are all elements [2,3,4,5,6].
To solve this, we will follow these steps −
- temp_range := y - x
- for i in range 0 to size of nums, do
- if |nums[i]| >= x and |nums[i]| <= y, then
- z := |nums[i]| - x
- if nums[z] > 0, then
- nums[z] := -nums[z]
- if |nums[i]| >= x and |nums[i]| <= y, then
- cnt := 0
- for i in range 0 to temp_range, do
- if i >= size of nums, then
- come out from loop
- if nums[i] > 0, then
- return False
- otherwise,
- cnt := cnt + 1
- if i >= size of nums, then
- if cnt is not same as (temp_range + 1), then
- return False
- return True
Let us see the following implementation to get better understanding −
Example
def solve(nums, x, y) : temp_range = y - x for i in range(0, len(nums)): if abs(nums[i]) >= x and abs(nums[i]) <= y: z = abs(nums[i]) - x if (nums[z] > 0) : nums[z] = nums[z] * -1 cnt = 0 for i in range(0, temp_range + 1): if i >= len(nums): break if nums[i] > 0: return False else: cnt += 1 if cnt != temp_range + 1: return False return True nums = [5,8,9,6,3,2,4] x = 2 y = 6 print(solve(nums, x, y))
Input
[5,8,9,6,3,2,4], 2, 6
Output
True
- Related Articles
- Check if list contains all unique elements in Python
- Check if the given array contains all the divisors of some integer in Python
- Java Program to Check if An Array Contains a Given Value
- Golang Program to Check if An Array Contains a Given Value
- Check if all array elements are distinct in Python
- Check if a given array contains duplicate elements within k distance from each in C++
- Check if elements of an array can be arranged satisfying the given condition in Python
- Java Program to Check if An Array Contains the Given Value
- Check if object contains all keys in JavaScript array
- Check if all elements of the array are palindrome or not in Python
- Check if an array contains the elements that match the specified conditions in C#
- Python - Check if all elements in a List are same
- Python - Check if all elements in a list are identical
- Python program to check if a string contains all unique characters
- Check if the array has an element which is equal to sum of all the remaining elements in Python

Advertisements