
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find All Strings Formed from Characters Mapped to Digits in Python
Suppose we have a character mapping as follows, here each digit, from 1 to 9, maps to few characters.
1 -> ['A', 'B', 'C'] 2 -> ['D', 'E', 'F'] 3 -> ['G', 'H', 'I'] 4 -> ['J', 'K', 'L'] 5 -> ['M', 'N', 'O'] 6 -> ['P', 'Q', 'R'] 7 -> ['S', 'T', 'U'] 8 -> ['V', 'W', 'X'] 9 -> ['Y', 'Z']
If we have a number, we have to change its digits with corresponding characters in given mapping list and show all generated strings. We should consider same character for every occurrence of a digit in the number. The given number will not contain 0.
So, if the input is like [4,3,5], then the output will be
JGM KGM LGM JHM KHM LHM JIM KIM LIM JGN KGN LGN JHN KHN LHN JIN KIN LIN JGO KGO LGO JHO KHO LHO JIO KIO LIO
To solve this, we will follow these steps −
- out := a new list
- temp := a new list
- char_map := a new map
- index := 0
- for each digit in inp, do
- if digit not in char_map, then
- char_map[digit] := index
- clear the temp list
- for i in range 0 to size of table[digit - 1], do
- if index is same as 0, then
- s := table[digit - 1, i]
- insert s at the end of out
- if index > 0 is, then
- for each string in out, do
- s := table[digit - 1, i]
- if char_map[digit] is not same as index, then
- s := string[char_map[digit]]
- string := string concatenate s
- insert string at the end of temp
- if char_map[digit] is not same as index, then
- s := table[digit - 1, i]
- if char_map[digit] is not same as index, then
- break
- for each string in out, do
- if index > 0 , then
- out := a copy of temp
- index := index + 1
- if index is same as 0, then
- return out
- if digit not in char_map, then
Example
Let us see the following implementation to get better understanding −
def findCombinations(inp, table): out = list() temp = list() char_map = dict() index = 0 for digit in inp: if digit not in char_map: char_map[digit] = index temp.clear() for i in range(len(table[digit - 1])): if index == 0: s = table[digit - 1][i] out.append(s) if index > 0: for string in out: s = table[digit - 1][i] if char_map[digit] != index: s = string[char_map[digit]] string = string + s temp.append(string) if char_map[digit] != index: break if index > 0: out = temp.copy() index += 1 return out mapping = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'], ['J', 'K', 'L'], ['M', 'N', 'O'], ['P', 'Q', 'R'], ['S', 'T', 'U'], ['V', 'W', 'X'], ['Y', 'Z']] inp = [4,3,5] res = findCombinations(inp, mapping) for it in res: print(it, end=" ")
Input
[4,3,5]
Output
JGM KGM LGM JHM KHM LHM JIM KIM LIM JGN KGN LGN JHN KHN LHN JIN KIN LIN JGO KGO LGO JHO KHO LHO JIO KIO LIO
Advertisements