2

Problem: Given a list of 3 numbers [4, 8, 15] generate a list of all possible arrangements of the numbers.

That's 3*3*3 = 27 unique entries from what I can gather. Something like:

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.

list(itertools.permutations([4,8,15],3)) for example only prints 6 values:

[(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?

PhD
  • 11,202
  • 14
  • 64
  • 112
  • `I tried ...`. So can you share the code [in your question](https://stackoverflow.com/posts/52194927/edit) so we can more accurately address your issue? – jpp Sep 06 '18 at 00:28
  • `list(itertools.product([4, 8, 15], repeat=3))`? – Sraw Sep 06 '18 at 00:31

3 Answers3

2

you are confusing permutations with product:

len(list(itertools.permutations([4,8,15],3)))
# return 6
len(list(itertools.product([4,8,15], repeat=3)))
# return 27
Lucas
  • 6,869
  • 5
  • 29
  • 44
0

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.

itertools.product([4,8,15],repeat=3) would return the permutations you want in your example.

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.

iajrz
  • 749
  • 7
  • 16
  • 1
    It won't work:) Notice `product`'s signature: `itertools.product(*iterables, repeat=1)`, your `3` will be considered as `iterables`. – Sraw Sep 06 '18 at 00:33
  • Thanks, it's been a while since I dabbled in python. – iajrz Sep 06 '18 at 00:35
-1

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")
JulianP
  • 97
  • 1
  • 11