Python: nested 'for' loops

前端 未结 5 1196
天涯浪人
天涯浪人 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 10:16

    Could use itertools:

    >>> for comb in itertools.combinations_with_replacement(range(9, -1, -1), 3):
            print comb
    
    (9, 9, 9)
    (9, 9, 8)
    (9, 9, 7)
    (9, 9, 6)
    ...
    (4, 0, 0)
    (3, 3, 3)
    (3, 3, 2)
    (3, 3, 1)
    (3, 3, 0)
    (3, 2, 2)
    (3, 2, 1)
    (3, 2, 0)
    (3, 1, 1)
    (3, 1, 0)
    (3, 0, 0)
    (2, 2, 2)
    (2, 2, 1)
    (2, 2, 0)
    (2, 1, 1)
    (2, 1, 0)
    (2, 0, 0)
    (1, 1, 1)
    (1, 1, 0)
    (1, 0, 0)
    (0, 0, 0)
    

    Or recursively, appending more and more digits until enough, which can more directly produce int objects instead of digit tuples (not sure whether that's what you actually need):

    def build(enough, prefix=0):
        if prefix >= enough:
            print(prefix)
            return
        for digit in range(prefix % 10 + 1) if prefix else range(1, 10):
            build(enough, prefix * 10 + digit)
    

    Demo (note it leaves out "000", not sure whether you'd want that anyway):

    >>> n = 3
    >>> build(10**(n-1))
    100
    110
    111
    200
    210
    211
    220
    221
    222
    300
    310
    311
    320
    321
    322
    330
    331
    332
    333
    400
    410
    411
    420
    

提交回复
热议问题