Combinations in Python without using itertools
Last Updated :
21 Jun, 2022
Itertools in Python is a module that produces complex iterators with the help of methods that work on iterators. This module works as a fast, memory-efficient tool that is used either by itself or in combination to form iterator algebra.
Printing Combinations Using itertools
Using Itertools we can display all the possible combinations of the string in a quite optimized way. To display the combination requires 2 parameters. First is the string and the second is the length of substrings needed. The following example makes all combinations for the string 'abc' using itertools.
Example:
Python3
# Import combinations from itertools
from itertools import combinations
def n_length_combo(arr, n):
# using set to deal
# with duplicates
return list(combinations(arr, n))
# Driver Function
if __name__ == "__main__":
arr = 'abc'
n = 2
print (n_length_combo([x for x in arr], n) )
Output[('a', 'b'), ('a', 'c'), ('b', 'c')]
Printing Combinations Without using itertools
A. Using recursion
To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.
Python3
# Function to create combinations
# without itertools
def n_length_combo(lst, n):
if n == 0:
return [[]]
l =[]
for i in range(0, len(lst)):
m = lst[i]
remLst = lst[i + 1:]
remainlst_combo = n_length_combo(remLst, n-1)
for p in remainlst_combo:
l.append([m, *p])
return l
# Driver code
if __name__=="__main__":
arr ="abc"
print(n_length_combo([x for x in arr], 2))
Output[['a', 'b'], ['a', 'c'], ['b', 'a'], ['b', 'c'], ['c', 'a'], ['c', 'b']]
B. By using iterations
In this, return the first combination of n elements from the string as it is, then other combinations are made by considering each element by its position. Each element is treated as unique based on its position, not on its value. So if the input elements are unique, there will be no repeat values in each combination.
Python3
import numpy
def n_length_combo(iterable, r):
char = tuple(iterable)
n = len(char)
if r > n:
return
index = numpy.arange(r)
# returns the first sequence
yield tuple(char[i] for i in index)
while True:
for i in reversed(range(r)):
if index[i] != i + n - r:
break
else:
return
index[i] += 1
for j in range(i + 1, r):
index[j] = index[j-1] + 1
yield tuple(char[i] for i in index)
# Driver code
print([x for x in n_length_combo("abc", 2)])
Output:
[('a', 'b'), ('a', 'c'), ('b', 'c')]
Similar Reads
Python - Itertools.Combinations_with_replacement() Itertools in Python refers to module provided in Python for the creation of iterators which helps in efficient looping, time and space efficiency as well. Itertools helps us to solve complex problems easily and efficiently. There are in general 3 types of iterators.Different types of iterators provi
2 min read
Itertools Combinations() function - Python The combinations() function in Python, part of the itertools module, is used to generate all possible combinations of a specified length from a given iterable (like a list, string, or tuple). Unlike permutations, where the order does matter, combinations focus only on the selection of elements, mean
2 min read
Python | Size Range Combinations in list The problem of finding the combinations of list elements of specific size has been discussed. But sometimes, we require more and we wish to have all the combinations of elements of all sizes in range between i and j. Letâs discuss certain ways in which this function can be performed. Method #1 : Usi
4 min read
Combinatoric Iterators in Python An iterator is an object that can be traversed through all its values. Simply put, iterators are data type that can be looped upon. Generators are iterators but as they cannot return values instead they yield results when they are executed, using the 'yield' function. Generators can be recursive jus
4 min read
Permutation and Combination in Python Python provides built-in methods to work with permutations and combinations using the itertools module. These are helpful in problems involving arrangement (order matters) and selection (order doesnât matter) of elements.Let's explore them one by one:PermutationA permutation is an arrangement of ele
2 min read