0

When I create the permutations below, there are 360 possibilities.

#Print permutations of 1 to 6 of a size 4
from itertools import permutations


possibilities = permutations([1,2,3,4,5,6], 4) #Permutations of size 6

sum_of_possibilities = 0

for i in list(possibilities):
    print(i)
    sum_of_possibilities = sum_of_possibilities +1

I would like to get 4 random permutations of these 360 and save each number in a different variable.

For examples:

Select these 4 permutations below

(3, 5, 6, 2)
(1, 6, 4, 3)
(4, 3, 1, 5)
(6, 5, 3, 4)

and save the first number 3 as x1; 5 as x2; 6 as x3; 2 as x4... 3 as x15 and 4 as x16.

#RESULTS

print(f'Total of possibilities are: {sum_of_possibilities}')

​print(possibilities[0])

Total of possibilities are: 360

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_13912\1726349991.py in <module>
      3 print(f'Total of possibilities are: {sum_of_possibilities}')
      4 
----> 5 print(possibilities[0])

TypeError: 'itertools.permutations' object is not subscriptable
2
  • Does this answer your question? Commented Feb 7, 2023 at 20:38
  • As a side note, generating all possible permutations becomes very costly very quickly for increasing population sizes. It might be worth consider whether this is really necessary, or if a simpler approach would work just as well, like picking random samples without replacement Commented Feb 7, 2023 at 20:56

1 Answer 1

0

Got it!

#Print permutations of 1 to 6 of a size 6
from itertools import permutations #import library to do permutations

size = 6

possibilities = list(permutations([1,2,3,4,5,6], size)) #Permutations of size 6

print(f'There are {len(possibilities)} possibilities to be analyzed\n')

print('The solutions are (i0, i1, i2, i3, i4, i5) = ')

solutions=0 #quantity of solutions found before start to calculate

for n in range(len(possibilities)):
    i=[]
    for j in range(size):
        i.append(possibilities[n][j])
        
    c1 = i[0]+i[2]+i[3]+i[4]
    c2 = i[0]+i[1]+i[3]+i[5]
    c3 = i[4]+i[1]+i[2]+i[5]
    if c1 == c2 and c1 == c3: #Test if the sums are the same
        sum = c1
        print(possibilities[n])
        solutions = solutions + 1
print(f'\n There are {solutions} possible solutions for this puzzle, where all the sum in the circle are equal to {sum}')

It's a math puzzle https://github.com/lstavares84/math_puzzles_in_python/blob/main/math_puzzle_1.ipynb

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.