 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Program to find list of all possible combinations of letters of a given string s in Python
Suppose we have a string s. We have to find all possible combinations of letters of s. If there are two strings with same set of characters, then show the lexicographically smallest of them. And one constraint is each character in s are unique.
So, if the input is like s = "pqr", then the output will be ['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']
To solve this, we will follow these steps −
- st_arr := a new list
- for i in range size of s - 1 to 0, decrease by 1, do- for j in range 0 to size of st_arr - 1, do- insert (s[i] concatenate st_arr[j]) at the end of st_arr
 
- insert s[i] at the end of st_arr
 
- for j in range 0 to size of st_arr - 1, do
- return st_arr
Example
Let us see the following implementation to get better understanding −
def solve(s): st_arr = [] for i in range(len(s)-1,-1,-1): for j in range(len(st_arr)): st_arr.append(s[i]+st_arr[j]) st_arr.append(s[i]) return st_arr s = "pqr" print(solve(s))
Input
"pqr"
Output
['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']
Advertisements
 