Program to find all possible strings typed using phone keypad in python

PythonServer Side ProgrammingProgramming

Suppose we have a string containing digits from 2-9. We have to find all possible letter combinations that the number could generate. One mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does map some characters but no letters.

1
2
a b c
3
d e f
4
g h i
5
j k l
6
m n o
7
p q r s
8
t u v
9
w x y z
*
0
#

For an example, if the given string is “49”, then the possible strings will be ['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz']

To solve this, we will follow these steps:

  • Define an array called solve to solve the problem recursively
  • solve method takes digits, characters, result, current_string and current_level, the function will be like
  • if current_level = length of digits, then add current string after the result, and return
  • for all characters i in characters[digits[current_level]]
    • perform solve(digits, characters, result, current_string + i, current_level + 1)
  • The actual function will be like
  • if digits length is 0, then return empty list
  • define one map to hold numbers and corresponding characters as a string
  • result := an empty list
  • call solve(digits, characters, result, “”, 0)

Let us see the following implementation to get better understanding:

Example

Live Demo

class Solution(object):
   def letterCombinations(self, digits):
      if len(digits) == 0:
         return []

      characters = {2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"}
      result = []
      self.solve(digits,characters,result)
      return result
   def solve(self, digits, characters, result, current_string="",current_level = 0):
      if current_level == len(digits):
         result.append(current_string)
      return
   for i in characters[int(digits[current_level])]:
self.solve(digits,characters,result,current_string+i,current_level+1)

ob1 = Solution()
print(ob1.letterCombinations("49"))

Input

"49"

Output

['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz']
raja
Published on 26-Nov-2020 08:14:00
Advertisements