Python: nested 'for' loops

前端 未结 5 1199
天涯浪人
天涯浪人 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条回答
  •  梦如初夏
    2021-02-07 09:59

    I would probably implement this recursively:

    def generate(max, digits):
        for d in range(max + 1):
            if digits == 1:
                yield d
            else:
                first = d * 10**(digits-1)
                for n in generate(d, digits - 1):
                    yield first + n
    

    The output:

    In : list(generate(3, 3))
    Out:
    [0,
     100,
     110,
     111,
     200,
     210,
     211,
     220,
     221,
     222,
     300,
     310,
     311,
     320,
     321,
     322,
     330,
     331,
     332,
     333]
    

提交回复
热议问题