Program to generate all possible strings by taking the choices in python

Suppose we have a string s of lowercase alphabet characters, other characters like "[", "|", and "]". Here "[a|b|c]" indicates either "a", "b", or "c" can be chosen as a possibility. We have to find a list of strings containing all possible values that s can represent. Here "[]" cannot be nested and may have any number of choices.

So, if the input is like s = "[d|t|l]im[e|s]", then the output will be ['dime', 'dims', 'lime', 'lims', 'time', 'tims']

To solve this, we will follow these steps:

  • if s is empty, then
    • return a list with blank string
  • n := size of s
  • seq := a new list, res := a new list
  • Define a function helper() . This will take pos
    • if pos is same as n, then
      • join each element present in seq and insert into res
    • otherwise,
      • if "[" in substring of s[from index pos to end], then
        • start := pos + index of "[" in substring of s[from index pos to end]
        • end := pos + index of "]" in substring of s[from index pos to end]
        • for each option in the substring of s from start to end splitted by "|", do
          • insert s[from index pos to start - 1] at the end of seq
          • insert option at the end of seq
          • helper(end + 1)
          • delete last two elements from seq
    • otherwise,
      • insert s[from index pos to end] at the end of seq
      • helper(n)
      • delete last element from seq
  • From the main method do the following:
  • helper(0)
  • return res in sorted order

Let us see the following implementation to get better understanding:


Live Demo

class Solution:
   def solve(self, s):
      if not s:
         return [""]
      n = len(s)

      def helper(pos):
         if pos == n:
            if "[" in s[pos:]:
               start = pos + s[pos:].index("[")
               end = pos + s[pos:].index("]")
               for option in s[start + 1 : end].split("|"):
                  helper(end + 1)

         seq = []
         res = []
         return sorted(res)

ob = Solution()
s = "[d|t|l]im[e|s]"




['dime', 'dims', 'lime', 'lims', 'time', 'tims']