This question already has answers here:
How do I generate all permutations of a list?
(40 answers)
Closed 8 years ago.
I want to write a recursive function p() that takes a list and returns a list of all permutations of the input list.
Ex.
>>>permutations([1, 2,3])
[[1, 2,3],[2, 1, 3],[2, 3, 1],[1, 3, 2],[3, 1, 2],[3, 2, 1]]
I want to recursively call on a sublist l[1:] for all permutations of all elements of the original input list except the first element, l[0], and then generate the permutations of the original list by adding l[0] to those permutations.
So far, I have
def p(list):
if len(list)==1 or 0:
return list
result = []
for i in list[1:]:
result.append(i + list[0])
result += [list]
return result
But I know something is wrong.... help please?
I don't know that is what you want but check it out
from itertools import permutations
l = [1, 2, 3, 4, 5]
new_l = list(permutations(l, len(l)))
it will output something like
[(1, 2, 3, 4, 5),
(1, 2, 3, 5, 4),
(1, 2, 4, 3, 5),
(1, 2, 4, 5, 3),
(1, 2, 5, 3, 4),
...
Hope this helps!
Related
This question already has answers here:
How to get all combinations of length n in python
(3 answers)
Closed 1 year ago.
I am trying to generate all possible 3 combinations from the set {1,2,3,4,5} using recursion.
Expected output: [[1,2,3],[1,2,4],[1,2,5],[2,3,4],[2,3,5],[3,4,5],[1,3,4],[1,3,5],[1,4,5],[2,4,5]]
The logic that I am using is that any 3-set combination will either have the first element in it or not have. I am also using the concatenation of lists. Example:
[[1,2,3]] + [[a,b]] gives [[1,2,3],[a,b]]
The below code that uses the above logic doesn't seem to work. I am self-learning so, if I make a mistake, please be patient with me. I am aware there are errors in my recursion. But, trying to backtrack the output in recursion problems is proving quite difficult for me.
Could you please let me know where could be the flaw in this program and guide me towards suitable resources where such types of questions can be better handled. What is the right way of thinking in such questions? Thanks a lot for helping.
Code:
sol = [1,2,3,4,5]
b=3
y= []
def combinations(sol, b):
global y
if len(sol) == b or len(sol)==1 :
return [sol]
y.append([[sol[0]] + combinations(sol[1:], b-1)] + combinations(sol[1:],b))
return y
print(combinations(sol,b)
Use the machinery provided in itertools:
from itertools import combinations
list(combinations(v, 3))
OUTPUT
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
You CAN do this, by having your function be a generator. At each step, you loop through the possible starting cells, then loop through the results returned by the next step in the recursion.
sol = [1,2,3,4,5]
b=3
def combinations(sol, b):
if b == 0:
yield []
else:
for i in range(len(sol)-b+1):
for j in combinations(sol[i+1:],b-1):
yield [sol[i]]+j
print(list(combinations(sol,b)))
Output:
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
I want my code to return, for every element in array, this array but without this one element.
Example: for array numbers=[1,2,3] I want output "[2,3]","[1,3]","[1,2]"
I've used this code:
examp = [1, 2, 3, 4, 5]
for number in examp:
print(str(number) + " MAIN")
subExp = examp
subExp.remove(number)
print(subExp)
but this one outputs (word "MAIN" is used as information which element is right now "subtracted" from array):
1 MAIN
[2, 3, 4, 5]
3 MAIN
[2, 4, 5]
5 MAIN
[2, 4]
For this code above I would expect this:
1 MAIN
[2, 3, 4, 5]
2 MAIN
[1, 3, 4, 5]
3 MAIN
[1, 2, 4, 5]
4 MAIN
[1, 2, 3, 5]
5 MAIN
[1, 2, 3, 4]
It's probably some stupid mistake from my side, but as a beginner in this topic, I coudn't find answer anywhere, so if there's any better way to do it, please help
The issue is this line:
subExp = examp
Here subExp isn't a copy of examp, but rather just another pointer just like examp to the list [1, 2, 3, 4, 5]. So in each iteration of your for loop you remove one entry of the list.
You can replace that line with:
subExp = examp.copy()
which will make a shallow copy of examp. Although this works for flat lists, you'd get in trouble for nested lists. In general you want to use copy package's
subExp = copy.deepcopy(examp)
EDIT: If you don't need to do the print line, then itertools.combinations() is the way to go. See https://docs.python.org/2/library/itertools.html#itertools.combinations for more info
For these you can use itertools:
import itertools
list(itertools.combinations([1, 2, 3,4,5],4))
# [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]
Iterate through the list, slicing out the current element:
examp = [7, False, "OOpS", 3.14159]
for i in range(len(examp)):
print(examp[:i] + examp[i+1:])
Output:
[False, 'OOpS', 3.14159]
[7, 'OOpS', 3.14159]
[7, False, 3.14159]
[7, False, 'OOpS']
You can create a range, then output arrays filtered by index
examp = [1, 2, 3, 4, 5]
for x in range(0, len(examp)):
print(f'iteration {x + 1} ->')
print([el for i, el in enumerate(examp) if i != x])
or using itertools
print(list(itertools.combinations(examp, len(examp) - 1)))
This question already has answers here:
How do I generate all permutations of a list?
(40 answers)
Closed 6 years ago.
I am currently working on a simple project on my own, and I stumbled on a problem:
I need to have a list of 4 numbers: say
L=[1,3,4,6]
I need a full list of rearrangements of the Numbers so:
L_arranged=[[1,3,4,6],[1,3,6,4],[1,6,3,4],...,[3,4,1,6]]
Any Ideas?
Even a theory would be useful, thank you :)
You're looking for itertools.permutations.
>>> from itertools import permutations
>>> [list(p) for p in permutations([1,3,4,6])]
[[1, 3, 4, 6], [1, 3, 6, 4], [1, 6, 3, 4], ..., [3, 4, 1, 6]]
If you don't need to mutate (edit) the results, you can cast the return straight to a list, yielding tuples
>>> list(permutations([1,3,4,6]))
[(1, 3, 4, 6), (1, 3, 6, 4), (1, 6, 3, 4), ..., (3, 4, 1, 6)]
Even faster, if you plan on using the results solely as an iterator, you don't need to cast it at all
>>> for p in permutations([1,3,4,6]):
... print(p)
(1, 3, 4, 6)
(1, 3, 6, 4)
(1, 6, 3, 4)
...
(3, 4, 1, 6)
I am looking for some help splitting an index from a list containing multiple values and creating a new list with separated values.
L = [(1, 2, 2, 3, 4, 4, 5, 5)]
>>>L[0]
(1, 2, 2, 3, 4, 4, 5, 5)
I need to split that single index into multiple indices in a new list such that:
L_Revised = [1, 2, 2, 3, 4, 4, 5, 5]
>>>L[0]
1
So that I can manipulate the individual indices. What code could I use for this?
Thanks for any help!
For a generalized case, where you can have more than one tuple in the list, you can flatten your list like this:
>>> l = [(1, 2, 3, 4, 5)]
>>> [item for tup in l for item in tup]
[1, 2, 3, 4, 5]
But if it's a single tuple element list, then probably other answer is easier.
I have a list [2,3,4]. How do I find all possible sequence of elements in the list?
So the output should be:
[2,3,4]
[2,4,3]
[3,2,4]
[3,4,2]
[4,2,3]
[4,3,2]
You can do this easily using itertools.permutations():
>>> from itertools import permutations
>>> list(permutations([2, 3, 4]))
[(2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 2, 3), (4, 3, 2)]
And if for some reason you need lists instead of tuples:
>>> map(list, permutations([2, 3, 4]))
[[2, 3, 4], [2, 4, 3], [3, 2, 4], [3, 4, 2], [4, 2, 3], [4, 3, 2]]
You are looking for permutations, something like this should work:
import itertools
itertools.permutations([2,3,4])
a start of a great lottery program except data would be formated as such
ist(permutations([2, 3, 4],[7,2,5],[8,1,4,9]))
the problem is that the first group is used to create numbers in first column only
the secound is for 2 column and 3rd is for 3rd
the output will be a set of 3 numbers just that the permutation is different
Just so you know:
def unique_perms(elems):
"""returns non-duplicate permutations
if duplicate elements exist in `elems`
"""
from itertools import permutations
return list(set(permutations(elems)))
But if you're doing something like this:
print len(unique_perms(elems))
Then try this:
def fac(n):
"""n!"""
if n == 1: return n
return n * fac(n -1)
def unique_perm_count(elems)
n = len(elems)
return fac(2 * n) / fac(n) ** 2