[Solved] How to generate numbers based on a pattern in python [closed]


This should work:

[int("4"*i + "0"*(n-i)) for n in range(0,31) for i in range(1,n+1)]

It generates 465 distinct integers:

4, 40, 44, 400, 440, ..., 444444444444444444444444444440, 444444444444444444444444444444

On Edit: A recursive approach works in the more general case:

def multiRepeats(chars,n,initial = True):
    strings = []
    if len(chars) == 0 or n == 0: return [""]
    c = chars[0]
    rest = chars[1:]
    base = 1 if initial else 0
    for i in range(base,n+1):
        head = c * i
        strings.extend([head + tail for tail in multiRepeats(rest,n-i,False)])
    return strings

def digitRepeats(digitString,n):
    return sorted([int(s) for s in multiRepeats(digitString,n)])

For example

>>> digitRepeats("420",4)
[4, 40, 42, 44, 400, 420, 422, 440, 442, 444, 4000, 4200, 4220, 4222, 4400, 4420, 4422, 4440, 4442, 4444]

To answer your original post, evaluate digitRepeats("40",30)

3

solved How to generate numbers based on a pattern in python [closed]