The Wayback Machine - https://web.archive.org/web/20230302101246/https://www.geeksforgeeks.org/python-non-overlapping-random-ranges/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Non-overlapping Random Ranges

Improve Article
Save Article
  • Last Updated : 10 Feb, 2023
Improve Article
Save Article

Sometimes, while working with Python, we can have problem in which we need to extract N random ranges which are non-overlapping in nature and with given range size. This can have applications in which we work with data. Lets discuss certain way in which this task can be performed.

Method : Using any() + randint() + loop This is brute force way in which this task can be performed. In this we extract random ranges using randint(), and check for non-repetition of number ranges using any() and loop. 

Python3




# Python3 code to demonstrate working of
# Non-overlapping Random Ranges
# Using loop + any() + randint()
import random
 
# initializing N
N = 7
 
# initializing K
K = 5
 
# Non-overlapping Random Ranges
# Using loop + any() + randint()
tot = 10000
res = set()
for _ in range(N):
  temp = random.randint(0, tot - K)
  while any(temp >= idx and temp <= idx + K for idx in res):
     temp = random.randint(0, tot - K)
  res.add(temp)
res = [(idx, idx + K) for idx in res]
 
# printing result
print("The N Non-overlapping Random ranges are : " + str(res))

Output : 

The N Non-overlapping Random ranges are : [(5347, 5352), (7108, 7113), (5479, 5484), (1906, 1911), (2228, 2233), (5206, 5211), (3260, 3265)]

Approach 2 : Using bisect and randint
 

Python3




import random
import bisect
 
def random_ranges(n, k, tot):
  ranges = []
  starts = [random.randint(0, tot-k) for _ in range(n)]
  starts.sort()
  for i in range(1, n):
    if starts[i] <= starts[i-1] + k:
      starts[i] = starts[i-1] + k + 1
  for start in starts:
    ranges.append((start, start + k))
  return ranges
 
n = 7
k = 5
tot = 10000
print(random_ranges(n, k, tot))

Output

[(751, 756), (1068, 1073), (1357, 1362), (2370, 2375), (2784, 2789), (4479, 4484), (7195, 7200)]

This approach uses bisect module to sort the start positions of the ranges and randint from random module to generate random start positions. The code then checks if the current start position is less than or equal to the previous start position + k, if so, it adjusts the current start position to the previous start position + k + 1.

Time complexity: O(nlogn) for sorting and O(n) for looping, so O(nlogn + n) in total.

Auxiliary Space: O(n) for storing the start positions and ranges.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!