![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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