Home > Net >  Three Letter Combinations Similar to a dictionary
Three Letter Combinations Similar to a dictionary

Time:09-21

I am trying to create a three letter combination. For example if I enter 'b' as my letter, I would start with the first alphabet 'a' and it will loop until all three combination is equal to 'b' aaa aab aba abb baa bab bba bbb

My output is incomplete because it is skipping some of the letter combination like "aab" and "bab".

import string
letter = input("Enter letter: ") # from a to letter

for i in range(ord('a'), ord(letter)   1):
    for j in range(ord('a'), ord(letter)   1):
        for k in range(ord('a'), j   1):
            print(chr(i), chr(j), chr(k))

enter image description here

CodePudding user response:

Using j 1 on the third nested loop was causing the bug in the code. If you want to generate all combinations like aaa aab aba abb baa bab bba bbb the simplest logic is to loop through all the letters.

import string
letter = input("Enter letter: ") # from a to letter

for i in range(ord('a'), ord(letter)   1):
    for j in range(ord('a'), ord(letter)   1):
        for k in range(ord('a'), ord(letter)   1): # edited here
            print(chr(i), chr(j), chr(k))

CodePudding user response:

The answer above is fine, here's slightly more generic approach:

from itertools import product

size = 3
letter = 'b'

for t in ((chr(c) for c in t) for t in product(range(97, ord(letter) 1), repeat=size)):
   print(*t)

You could change size or letter and the solution remains correct. For example:

size = 2
letter = 'c'

Output:

a a
a b
a c
b a
b b
b c
c a
c b
c c

Note: user @MohammedTehrani provides an even cleaner use of product() that works very well in this particular case.

CodePudding user response:

You can use the product method in itertools package

def perm(seq, n):
    from itertools import product
    for perm in product(seq, repeat=n):
        print(''.join(perm))

perm("ab", 3)
  • Related