简体   繁体   中英

How to find all the possible combinations of a range in Python?

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
  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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM