Python: nested 'for' loops

前端 未结 5 1206
天涯浪人
天涯浪人 2021-02-07 09:47

I\'d like to go through all n-digit numbers such that second digit of the number is always lower or equal to the first, third is lower or equal to the second etc. I can get this

5条回答
  •  旧时难觅i
    2021-02-07 10:06

    A simple recursive approach:

    def ordered_digits_generator(numDigits,min=1,max=9):
        for first in range(min,max+1):
            if numDigits == 1:
                 yield first
            else:
                 addend = first*10**(numDigits-1)
                 for rest in ordered_digits(numDigits-1,min=0,max=first):
                     yield addend+rest
    

    Then called via:

    for number in ordered_digits_generator(10):
        print number
    

    works as expected.

    The mathematician's approach

    The itertools package already has logic which essentially already implements this recursion. Presumably better than we can, with significant testing. So we can use it as follows:

    import itertools
    def ordered_digits_combo(numDigits):
        exponent = [10**i for i in range(0,numDigits)]
    
        for subset in itertools.combinations(range(0,numDigits+9),numDigits):
            if subset[numDigits-1]>numDigits-1:
                v = 0
                for i in range(0,numDigits):
                    v += exponent[i]*(subset[i]-i)
                yield v
    

    Given an ordered subset a[0] of {0,1,...,n+8}, we pick the number with the ith digit from the right equal to a[i]-i. We have to exclude the case a[n-1]==n-1 because that consists of he number with all zeros.

提交回复
热议问题