So i want combination of all number from 1 to 5 in 2 length. I am using below code to get it done.
from itertools import combinations_with_replacement
# Get all combinations of [1, 2, 3] and length 2
comb = combinations_with_replacement([1, 2, 3, 4], 2)
# Print the obtained combinations
for i in list(comb):
print (i)
the result i get is:
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 2)
(2, 3)
(2, 4)
(3, 3)
(3, 4)
(4, 4)
but it is skipping some numbers like (2,1), (3,1), (3,2)
can anyone tell me how can i get all combination including also (1,2), (2,1) which usually the code skips.
Thanks
You have 8 objects: A, B, C, D, E, F, G, H All their permutations with repetitions with a sample size of 2 objects: AA AB BA AC CA AD DA AE EA AF FA AG GA AH HA BB BC CB BD DB BE EB BF FB BG GB BH HB CC CD DC CE EC CF FC CG GC CH HC DD DE ED DF FD DG GD DH HD EE EF FE EG GE EH HE FF FG GF FH HF GG GH HG HH
You want itertools.product
. combinations
never care for the order of elements, _with_replacement
just allows duplicates:
from itertools import product
comb = product([1, 2, 3, 4], repeat=2)
for i in comb: # no list conversion needed
print(i)
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
(4, 4)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.