1

I am trying to create a Python program where it accepts a string and displays permutations based on that.

For example.

If the user enters "[AAA] Grim" it should generate words starting from "aaa Grim" then "aab Grim" then "aac Grim" to "zzz Grim" etc. Or if the user enter "[AA] Grim" it should generate "aa Grim", "ab Grim", "ac Grim" to "zz Grim"

Sorry for the unclear question title. I'm not sure on how to word what I require without an example. :)

georg
  • 211,518
  • 52
  • 313
  • 390
Grim Reaper
  • 550
  • 1
  • 5
  • 18
  • 5
    And if the user enters "Grim Reaper"? Anyway, look at [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product). You can apply it to [`string.ascii_lowercase`](http://docs.python.org/2/library/string.html#string.ascii_lowercase) or `ascii_uppercase`. – Lev Levitsky Apr 24 '13 at 10:25
  • I've edited your title and tags. Also, do you have any ideas how to approach the problem? – georg Apr 24 '13 at 10:31

3 Answers3

1
input = '[AAA] Grim'
n = len(input.split(' ')[0]) - 2
s = input[n+2:]
a = [''.join(x)+s for x in itertools.product(string.ascii_lowercase, repeat=n)]
Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
0

If I understood what you meant the following will do:

import re
import string
import itertools

user_in = input("Enter string: ")
p_len = user_in.index(']') - user_in.index('[')
text = user_in[user_in.index(']')+1:]
print('\n'.join([ ''.join(p) + text for p in itertools.combinations_with_replacement(string.ascii_lowercase,r=p_len-1)]))

Will produce (an extract):

Enter string: [AA] Grim
aa Grim
ab Grim
ac Grim
ad Grim
ae Grim
HennyH
  • 7,794
  • 2
  • 29
  • 39
0
>>> import string
>>> ltrs = string.lowercase
>>> [''.join([a,b]) for a in ltrs for b in ltrs]

The code is from here: https://mail.python.org/pipermail/tutor/2005-July/040117.html

I found it and it works great!

Keaser
  • 351
  • 3
  • 6