1

This is more of a math question than Python, but if I have a range 0-100, how would I go about iterating through all the possible ranges in this? For example, the lower bound could be 0, and then the upper could be anything from 1-100 and so on.

Would something like this cover all possibilities?

lower = 0
upper = 100
for i in range(0,100):
    for z in range(lower,upper):
       print("Range is" + str(z) +":" + str(upper))
    
    lower = lower +1
    upper = upper -1
Lehman2020
  • 637
  • 7
  • 22
  • Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Itamar Mushkin Jun 21 '20 at 06:50

3 Answers3

2
  1. Checkout itertools.combinations:
itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

The combination tuples are emitted in lexicographic ordering according to the >order of the input iterable. So, if the input iterable is sorted, the >combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So >if the input elements are unique, there will be no repeat values in each >combination.

import itertools
arr = list(itertools.combinations(range(1,100), 2))
  1. Using For loops

For loops

arr = []
for i in range(1,101):
    for j in range(1,101):
        arr.append((i,j))
print(arr)
Equinox
  • 6,483
  • 3
  • 23
  • 32
1

Your questions is essentially all combinations of 2 numbers from 0-100. So 100 choose 2 different combinations. Python has itertools.combinations for this:

for lower, upper in itertools.combinations(range(100), 2):
    # do something with lower and upper
busybear
  • 10,194
  • 1
  • 25
  • 42
0

If you want to implement something of your own (don't want to use itertools as mentioned in other answers), here's something that will work:

lower = 0
upper = 10

for range_size in range(1, upper-lower+1):
  for j in range(lower, upper):
    if j+range_size > upper:
      break
    print(f"Range: [{j}, {j+range_size}]")

The outer loop iterates all the possible size of ranges, which can be as small as 1 and as large as upper - lower. Note that the +1 is to make sure upper limit is also included in range.

The inner loop then starts from the lower bound and print all the ranges of size range_size.

Edit: If you want to get a sorted output like itertools.combinations, you can store the values in an array and sort that array.

Moosa Saadat
  • 1,159
  • 1
  • 8
  • 20