How to generate all possible arrangements of numbers from a list in Python?
How to generate all possible arrangements of numbers from a list in Python?
Problem: Given a list of 3 numbers [4, 8, 15]
generate a list of all possible arrangements of the numbers.
[4, 8, 15]
That's 3*3*3 = 27
unique entries from what I can gather. Something like:
3*3*3 = 27
4,4,4
4,4,8
4,4,15
4,8,4
4,8,8
4,8,15
4,15,4
4,15,8
4,15,15
...
I tried using itertools.permutations
and itertools.combinations
but I can't get all 27 values.
itertools.permutations
itertools.combinations
list(itertools.permutations([4,8,15],3))
for example only prints 6 values:
list(itertools.permutations([4,8,15],3))
[(4, 8, 15), (4, 15, 8), (8, 4, 15), (8, 15, 4), (15, 4, 8), (15, 8, 4)]
[(4, 8, 15), (4, 15, 8), (8, 4, 15), (8, 15, 4), (15, 4, 8), (15, 8, 4)]
Is there something that's available out of the box or is this more of a "roll your own" problem?
I tried ...
list(itertools.product([4, 8, 15], repeat=3))
?– Sraw
Sep 6 '18 at 0:31
list(itertools.product([4, 8, 15], repeat=3))
3 Answers
3
you are confusing permutations
with product
:
permutations
product
len(list(itertools.permutations([4,8,15],3)))
# return 6
len(list(itertools.product([4,8,15], repeat=3)))
# return 27
Ahhh...that makes sense...
– PhD
Sep 6 '18 at 0:33
The answer is still in itertools. The function called product
does the trick; it takes two arguments: first is the iterable which has the usable elements, second is the amount of times the iterable can repeat itself.
product
itertools.product([4,8,15],repeat=3)
would return the permutations you want in your example.
itertools.product([4,8,15],repeat=3)
The reason permutations
or combinations
don't work for you is because they don't allow items to repeat themselves; product
calculates the cartesian product, which allows for repetition of items.
permutations
combinations
product
It won't work:) Notice
product
's signature: itertools.product(*iterables, repeat=1)
, your 3
will be considered as iterables
.– Sraw
Sep 6 '18 at 0:33
product
itertools.product(*iterables, repeat=1)
3
iterables
Thanks, it's been a while since I dabbled in python.
– iajrz
Sep 6 '18 at 0:35
This code prints what you requested :)
list = [4,8,15]
for i in range(len(list)):
for j in range (len(list)):
for k in range (len(list)):
print ("("+str(list[i]) +","+str(list[j])+","+str(list[k])+")n")
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I tried ...
. So can you share the code in your question so we can more accurately address your issue?– jpp
Sep 6 '18 at 0:28