How to get all possible combinations with python

Python is rich with wonderful standard library so you do not have to write everything from the very beginning. With permutations from iterators we can get wonderful and useful result with less code

>In this example code we get the user input as string

> Get the user input length

> Then run a for loop based on the user input str length

> get the combinations with permutation with store the combination in a list

Like this

Enter your word or sentence or number: 123
['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']



from itertools import permutations
user_input=str(input("Enter your word or sentence or number: "))
l=len(user_input)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(user_input,i))
	for element in a:
		x=(''.join(element))
		combinations.append(x)
print(combinations)


We can make this more wonderful to print out with pprint. Also print out all combinations from a list.


from itertools import permutations
from pprint import pprint
# flower names
flower_names = ["rose","orchid", "sunflower"]

l=len(flower_names)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(flower_names,i))
	combinations.append(a)
pprint(combinations)


You will get this result on running this code

[[('rose',), ('orchid',), ('sunflower',)],
 [('rose', 'orchid'),
  ('rose', 'sunflower'),
  ('orchid', 'rose'),
  ('orchid', 'sunflower'),
  ('sunflower', 'rose'),
  ('sunflower', 'orchid')],
 [('rose', 'orchid', 'sunflower'),
  ('rose', 'sunflower', 'orchid'),
  ('orchid', 'rose', 'sunflower'),
  ('orchid', 'sunflower', 'rose'),
  ('sunflower', 'rose', 'orchid'),
  ('sunflower', 'orchid', 'rose')]]

Related Posts

Calculate time dilation with python
June 16, 2024

In this example imagine two object one is Earth And another object is traveling in the space \[ t_0 = t \sqrt{1 – \frac{v^2}{c^2}} \] t0: Represents the dilated time experienced by the object which is traveling or seems traveling from earth t: Time passed on earth v: Velocity of the traveling object. c: Speed […]

How to convert text to sentence with python and nltk
June 16, 2024

We can easily convert text to sentence in python with nltk by tokenize sentence.. First install nltk Download nltk data . NLTK requires data files for tokenization. run the code in a python program to download the data. import nltk nltk.download(‘punkt’) Copy Code After download the necessary data from nltk import tokenize text=”In the symphony […]

Easy Temperature Conversions with Python: A Beginner’s Guide (Celsius, Fahrenheit, Kelvin)
June 16, 2024

Basic Temperature Conversion Program This program takes a temperature input from the user, identifies the scale (Celsius, Fahrenheit, Kelvin), and converts it to the other two scales. Let’s break down the code step-by-step. For higher accuracy in the Kelvin scale use 273.15 instead of 273 x = str(input(“Enter in which scale you measured temperature (Celsius, […]