Python: nested 'for' loops

前端 未结 5 1197
天涯浪人
天涯浪人 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:07

    I implemented @iFlo's suggestion as commented originally. It's not hyper efficient but it certainly doesn't take ages.

    def digit_test(n):
        while n > 9:
            if (n % 100 / 10) < (n % 10): return False
            n /= 10
        return True
    
    # under a second to construct a list of all numbers below 1000000 meeting the criteria
    candidates = [x for x in xrange(1,1000000) if digit_test(x)]
    
    # should be 8001 elements, consistent with other algorithms
    print len(candidates)
    

提交回复
热议问题