regex - How to generate numbers based on a pattern in python -
i have generate integers based on pattern.
example, have generate numbers that contain 4's , 0's , start 1 or more 4's , end 0 or more 0's (upto 30 digit numbers)
want code in python (2.7) only. don't want check pattern. want generate numbers in pattern
this should work:
[int("4"*i + "0"*(n-i)) n in range(0,31) in range(1,n+1)]
it generates 465 distinct integers:
4, 40, 44, 400, 440, ..., 444444444444444444444444444440, 444444444444444444444444444444
on edit: recursive approach works in 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 in range(base,n+1): head = c * strings.extend([head + tail tail in multirepeats(rest,n-i,false)]) return strings def digitrepeats(digitstring,n): return sorted([int(s) 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 original post, evaluate digitrepeats("40",30)
Comments
Post a Comment