1

I would like to make N nested for loops in python. E.g.:

for i in range(1,100):
    block1=i
    for j in range(1+i,100-i):
        block2=j
        for k in range(1+j,100-j):

        . . . 
            nth for loop:
                for nth in range(1+(prior for loop value),100-(prior for loop value))

In this specific instance, what I am trying to do is to check all possible combinations of values for a group of n variables, given that the variables be integers between 1 and 100. For example, if n is 3, then I want to check all possible combinations such as: 1,2,3 1,2,4 1,2,5 . . . 97,98,99.

Similarly if n is 4, I'd want to check: 1,2,3,4 1,2,3,5 1,2,3,6 . . . 96,97,98,99

(I don't need to check multiple instances of the same number. E.g. if n=3, 25,25,25 would be a wasted calculation.)

I would then perform some calculation using these n variables.

Thank you and please let me know if I could provide further clarification.

5
  • 2
    Without knowing more about your problem, recursion seems like a possible solution. Commented Oct 23, 2015 at 12:08
  • Seems like what you really want is to loop over all sorted n-tuples with unique numbers between 1 and 99. Better make it a single for loop. Commented Oct 23, 2015 at 12:08
  • provide more info about your problem. What you want to achieve? Commented Oct 23, 2015 at 12:11
  • If you tell us what the last nested loop is supposed to do, maybe we could suggest an alternative algorithm that would actually work. Commented Oct 23, 2015 at 12:13
  • This is also known as the XY Problem. Commented Oct 23, 2015 at 12:23

1 Answer 1

1

The itertools module has tools for iteration. Normally for nested for loops you think of itertools.product but as @RemcoGerlich points out, it seems like you just want to generate increasing n-tuples in lexicographic order. itertools.combinations is made to order for this.

itertools.combinations(iterable, r) Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. 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.

Try itertools.combinations(range(1,100), n)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.