Finding permuations and combinations using Python - python

I have 2 variables - a and b. I need to fill up k places using these variables. So if k = 3 output should be
[a,a,a], [a,a,b] , [a,b,a], [b,a,a], [a,b,b], [b,a,b], [b,b,a] and [b,b,b]
Input - k
Output - All the combinations
How do I code this in Python? Can itertools be of any help here?

>>> import itertools
>>> list(itertools.product('ab', repeat=3))
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'b', 'a'), ('b', 'b', 'b')]

def genPerm(varslist, pos,resultLen, result, resultsList)
if pos>resultLen:
return;
for e in varslist:
if pos==resultLen:
resultsList.append(result + [e]);
else
genPerm(varsList, pos+1, resultLen, result + [e], resultsList);
Call with:
genPerm([a,b], 0, resLength, [], resultsList);

Related

Using itertools product but needing combination behavior

I am trying to generate a list of possible strings of characters from input, accounting for wildcards "?" and "*". The ordering of list items should not matter, meaning if ABC already exists in the list, then I do not want to add ACB, or any other ordering (processing speed issue). The code I am using is below:
import itertools
from itertools import permutations
#####################################################
def getWordsFromTiles(tiles, word):
#####################################################
return all(word.count(i) <= tiles.count(i) for i in word)
#####################################################
Main
#####################################################
chars = A?*
wilds = [
('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')
if char == "?" or char == "*" else (char) for char in chars]
for p in itertools.product(*wilds):
x = ''.join(p)
hits.extend([word for word in data if getWordsFromTiles(x.upper(), word) and word not in hits])
This generates a list like the following:
A,A,A
A,A,B
A,A,C
.....
A,B,A
I actually do not care about the order of these list, so I would like to not have A,B,A when I have already generated "A,A,B. Any ideas how to implement this?
actually do not care about the order of these list, so I would like to not have A,B,A when I have already generated "A,A,B".
Is this what you are looking for?
from itertools import combinations_with_replacement
s = ['A','B','C','D']
list(combinations_with_replacement(s,3))
[('A', 'A', 'A'),
('A', 'A', 'B'),
('A', 'A', 'C'),
('A', 'A', 'D'),
('A', 'B', 'B'),
('A', 'B', 'C'),
('A', 'B', 'D'),
('A', 'C', 'C'),
('A', 'C', 'D'),
('A', 'D', 'D'),
('B', 'B', 'B'),
('B', 'B', 'C'),
('B', 'B', 'D'),
('B', 'C', 'C'),
('B', 'C', 'D'),
('B', 'D', 'D'),
('C', 'C', 'C'),
('C', 'C', 'D'),
('C', 'D', 'D'),
('D', 'D', 'D')]

n-fold Cartesian product on a single list in Python [duplicate]

This question already has answers here:
Generating permutations with repetitions
(6 answers)
Closed 8 months ago.
How to compute the n-fold Cartesian product on a list, that is, A × ... × A (n times), in an elegant (concise) way in Python?
Examples:
>>> l = ["a", "b", "c"]
>>> cart_prod(l, 0)
[]
>>> cart_prod(l, 1)
[('a',), ('b',), ('c',)]
>>> cart_prod(l, 2)
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> cart_prod(l, 3)
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'),
('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'),
('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]
I came up with the following iterative solution:
def cart_prod(l, n):
if n == 0:
return [] # compute the result for n = 0
# preliminarily, create a list of lists instead of a list of tuples
res = [[x] for x in l] # initialize list with singleton tuples (n = 1)
for i in range(n-1):
res = [r + [x] for r in res for x in l] # concatenate each n-1 tuple with each element from a
res = [tuple(el) for el in res] # turn the list of lists into a list of tuples
return res
This code does the job, but is there a shorter, possibly one-liner definition, maybe a nested list comprehension or a lambda expression? I am interested in more compact solutions, not necessarily more readable ones.
This question is not a duplicate of Get the cartesian product of a series of lists?. I do not want the Cartesian product of a series of lists crossed with each other. I want the Cartesian product of a single list crossed n-times with itself, where n is a parameter given to the function.
itertools.product takes a keyword argument to indicate the given arguments should be repeated.
>>> from itertools import product
>>> list(product([1,2], repeat=0))
[()]
>>> list(product([1,2], repeat=1))
[(1,), (2,)]
>>> list(product([1,2], repeat=2))
[(1, 1), (1, 2), (2, 1), (2, 2)]
This works with multiple iterables as well.
# Equivalent to list(product([1,2], ['a', 'b'], [1,2], ['a', 'b']))
>>> list(product([1,2], ['a', 'b'], repeat=2))
[(1, 'a', 1, 'a'), (1, 'a', 1, 'b'), (1, 'a', 2, 'a'), (1, 'a', 2, 'b'), (1, 'b', 1, 'a'), (1, 'b', 1, 'b'), (1, 'b', 2, 'a'), (1, 'b', 2, 'b'), (2, 'a', 1, 'a'), (2, 'a', 1, 'b'), (2, 'a', 2, 'a'), (2, 'a', 2, 'b'), (2, 'b', 1, 'a'), (2, 'b', 1, 'b'), (2, 'b', 2, 'a'), (2, 'b', 2, 'b')]

I need your help about a list

For example, I have a list like ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
In this list, I want to take elements that form () with 'A' elements.
This means, I want to take elements ('A', 'B') and ('A', 'C')
Not 'A', 'B' or ('C', 'D')
How can I get this?
l = ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
[x for x in l if type(x) == tuple and 'A' in x]
I would use a conditional list comprehension. I check if 'A' is in the list and if it is and the content isn't only A (hence the len check), then add it to the list.
temp = ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
results = [i for i in temp if 'A' in i and len(i) > 1]
print(results)
You can loop through like this:
new_lst = []
lst = ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
for i in lst:
if len(i) > 1 and i[0] == "A":
new_lst.append(i)
print new_lst

All combinations of list wIthout itertools

I'm trying to make a recursive function that finds all the combinations of a python list.
I want to input ['a','b','c'] in my function and as the function runs I want the trace to look like this:
['a','b','c']
['['a','a'],['b','a'],['c','a']]
['['a','a','b'],['b','a','b'],['c','a','b']]
['['a','a','b','c'],['b','a','b','c'],['c','a','b','c']]
My recursive function looks like this:
def combo(lst,new_lst = []):
for item in lst:
new_lst.append([lst[0],item])
print([lst[0],item])
return combo(new_lst,lst[1:])
The right answer is that you should use itertools.combinations. But if for some reason you don't want to, and want to write a recursive function, you can use the following piece of code. It is an adaptation of the erlang way of generating combinations, so it may seem a bit weird at first:
def combinations(N, iterable):
if not N:
return [[]]
if not iterable:
return []
head = [iterable[0]]
tail = iterable[1:]
new_comb = [ head + list_ for list_ in combinations(N - 1, tail) ]
return new_comb + combinations(N, tail)
This a very elegant way of thinking of combinations of size N: you take the first element of an iterable (head) and combine it with smaller (N-1) combinations of the rest of the iterable (tail). Then you add same size (N) combinations of the tail to that. That's how you get all possible combinations.
If you need all combinations, of all lengths you would do:
for n in range(1, len(iterable) + 1):
print(combinations(n, iterable))
Seems that you want all the product of a list, you can use itertools.product within the following function to return a list of generators:
>>> from itertools import product
>>> def pro(li):
... return [product(l,repeat=i) for i in range(2,len(l)+1)]
...
>>> for i in pro(l):
... print list(i)
...
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]

How to use itertools to compute all combinations with repeating elements? [duplicate]

This question already has an answer here:
Which itertools generator doesn't skip any combinations?
(1 answer)
Closed 8 years ago.
I have tried to use itertools to compute all combinations of a list ['a', 'b', 'c'] using combinations_with_replacement with repeating elements. The problem is in the fact that the indices seem to be used to distinguish the elements:
Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sort order. So, if the input
iterable is sorted, the combination tuples will be produced in sorted
order.
Elements are treated as unique based on their position, not on their
value. So if the input elements are unique, the generated combinations
will also be unique.
Sot this code snippet:
import itertools
for item in itertools.combinations_with_replacement(['a','b','c'], 3):
print (item)
results in this output:
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'c')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'c')
('c', 'c', 'c')
And what I need is the combination set to contain elements like: ('a', 'b', 'a') which seem to be missing. How to compute the complete combination set?
It sounds like you want itertools.product:
>>> from itertools import product
>>> for item in product(['a', 'b', 'c'], repeat=3):
... print item
...
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'a')
('a', 'c', 'b')
('a', 'c', 'c')
('b', 'a', 'a')
('b', 'a', 'b')
('b', 'a', 'c')
('b', 'b', 'a')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'a')
('b', 'c', 'b')
('b', 'c', 'c')
('c', 'a', 'a')
('c', 'a', 'b')
('c', 'a', 'c')
('c', 'b', 'a')
('c', 'b', 'b')
('c', 'b', 'c')
('c', 'c', 'a')
('c', 'c', 'b')
('c', 'c', 'c')
>>>
For such small sequences you could use no itertools at all:
abc = ("a", "b", "c")
print [(x, y, z) for x in abc for y in abc for z in abc]
# output:
[('a', 'a', 'a'),
('a', 'a', 'b'),
('a', 'a', 'c'),
('a', 'b', 'a'),
('a', 'b', 'b'),
('a', 'b', 'c'),
('a', 'c', 'a'),
('a', 'c', 'b'),
('a', 'c', 'c'),
('b', 'a', 'a'),
('b', 'a', 'b'),
('b', 'a', 'c'),
('b', 'b', 'a'),
('b', 'b', 'b'),
('b', 'b', 'c'),
('b', 'c', 'a'),
('b', 'c', 'b'),
('b', 'c', 'c'),
('c', 'a', 'a'),
('c', 'a', 'b'),
('c', 'a', 'c'),
('c', 'b', 'a'),
('c', 'b', 'b'),
('c', 'b', 'c'),
('c', 'c', 'a'),
('c', 'c', 'b'),
('c', 'c', 'c')]

Categories

Resources