2

So I am given a string of digits of variable length and I need to find all possible number combinations using the digits in that string where only the digits in between may be changed, for example:

if I am given 123, I need to find the combinations of 1x2y3 where x, y are any digits.

if I am given 5312, I need to find the combinations of 5a3b1c2 where a, b, c are any digits.

I'm thinking this is possible using python's re.escape function, this is as far as I've come:

#Given the digits '123' from STDIN

#create a string "1\d2\d3"
my_regex_string = '\d'.join(input().split())

#Set x as starting point, set y as limit (not the most efficient)
x = 10**(len(my_regex_string)-1) * int(my_regex_string[0])
y = 10**(len(my_regex_string)-1) * (int(my_regex_string[0]) + 1)

while x < y:
    if bool(re.match(re.escape(p), str(x)))
        print(x)
    x+=1

I need feedback, does my approach make sense? Is this task doable with regex or do I need another approach?

5
  • 2
    Why don't you use itertools? Commented Apr 18, 2018 at 19:14
  • 1
    And why do you want to use regex? Commented Apr 18, 2018 at 19:28
  • 3
    Using regex for this is a really bad choice. Use itertools.product. Commented Apr 18, 2018 at 19:31
  • Are you trying to find the total number, or get a list of all solutions? Commented Apr 18, 2018 at 20:11
  • Are you looking to create a regex that can just match these combinations, or to just create the combinations ? A regex would be 1\d2\d3, etc. To generate, its just simple nested loops that you don't need anything special to do it with. Commented Apr 18, 2018 at 20:55

2 Answers 2

3

I think, like what the wolfrevokcats said, the pythonic way of doing this is to use itertools.product function. Something like this code:

from itertools import product

s = input()
r = "{}".join(list(s))
c = [int(r.format(*f)) for f in product(range(0,10), repeat=len(s)-1)]
Sign up to request clarification or add additional context in comments.

1 Comment

Really clean solution! Good job
1

Here's one solution using itertools, probably not the most sophisticated but it works:

>>> import itertools
>>> x = map(lambda z: [s[i] + str(z[i]) for i in range(len(s)-1)] + [s[-1]], list(itertools.product(range(10), repeat=len(s)-1)))
>>> y = map(lambda z: "".join(z), x)
>>> list(y)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.