gvdb
gvdb

Reputation: 351

Generate all possibilities for a string where some letters can be numbers, in Python

Say I have a string like this.

sentence = "i like to go fishing on saturday"

And some letters can be numbers, in the tradition of '1337' speak i.e. h3110, h0w 4r3 y0u?

However I want to get all possible combinations where some letters are converted to numbers, but others are not. Some examples with the above sentence.

"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.

How could I write in Python a dictionary of substitutions for each letter and then a way to generate all possible combinations for the sentence?

Upvotes: 1

Views: 197

Answers (3)

Paul Panzer
Paul Panzer

Reputation: 53079

You can build the dictionary from pairs and then use itertools.product for all combinations:

import itertools

# 1: write down pairs
pairs = ['a4', 't7', 'e3'] # etc.
# 2: make dict; it will be convenient to store both letter and substitute as value
pd = {p[0]:p for p in pairs}
# 3: replace all eligible letters with the appropriate pair and
#    use itertools.product
[''.join(c) for c in itertools.product(*(pd.get(i, i) for i in 'i like to go fishing on saturday'))]
# ['i like to go fishing on saturday', 'i like to go fishing on saturd4y', 
#  'i like to go fishing on sa7urday', 'i like to go fishing on sa7urd4y',
#  'i like to go fishing on s4turday', 'i like to go fishing on s4turd4y',
#  'i like to go fishing on s47urday', 'i like to go fishing on s47urd4y',
#  'i like 7o go fishing on saturday', 'i like 7o go fishing on saturd4y',
#  'i like 7o go fishing on sa7urday', 'i like 7o go fishing on
#  ...

Upvotes: 2

Brett7533
Brett7533

Reputation: 342

You can create a dictionary manual. But get all combinations with itertools.combinations

from itertools import combinations

sentence = "i like to go fishing on saturday"

d = {'l' : '1',
     'e' : '3',
     't' : '7'}

for l in range(len(d)):
    for x in combinations(d, l):
        for k in x:
            s = sentence.replace(k, d[k])
            print(s)

But this version will replace all t to 7. Not match all your requirement.

Upvotes: 1

Prune
Prune

Reputation: 77850

Write a list of substitutions, such as

[
  [1, 'l'],
  [3, 'e'],
  [4, 'a'],
  ...
]

Next, divide your text into sections, separating any letter that you can substitute. For instance, "fishing on saturday" becomes

[ "fishing ", "o", "n s", "a", "turd", "a", "y"]

Now, bring in the substitution lists for all appropriate letters: o a a in this case. Use itertools.product to generate all of the possible combinations.

Is that enough to get you started? Implementation is left as an exercise for the student.

Upvotes: 1

Related Questions