Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, combinations, permutations without repeat

Python. I have two lists, same length. The idea is to build paired data (for regression analysis). I figured out loops and it look like this.

a=(1,3,5,7)   #first list
b=(2,4,6,10)  #second list
w=zip(a,b)    #paired values from both lists

i=0
j=0
for each in w:
    x= w[i]
    for that in xrange(i,len(w)-1):
        i+=1
        print x, w[i]
    j+=1
    i=j

The output is as I was expected - first pair together with second, third.. so on, then second pair with the third, fourth.. and so on (skipping the combination between second pair and first pair, because it is kinda the same as combination of first and second pairs...)

(1, 2) (3, 4)
(1, 2) (5, 6)
(1, 2) (7, 10)
(3, 4) (5, 6)
(3, 4) (7, 10)
(5, 6) (7, 10) [..] and so on as I was expecting.

The question is - is there some other, shorter, optimized ways how to rewrite this code, maybe using itertools?

like image 589
Didzis Lauva Avatar asked Sep 15 '25 10:09

Didzis Lauva


2 Answers

You can use itertools.combinations with itertools.izip:

>>> from itertools import izip, combinations
>>> for a, b in combinations(izip(a, b), 2):
        print a, b
...     
(1, 2) (3, 4)
(1, 2) (5, 6)
(1, 2) (7, 10)
(3, 4) (5, 6)
(3, 4) (7, 10)
(5, 6) (7, 10)
like image 109
Ashwini Chaudhary Avatar answered Sep 17 '25 01:09

Ashwini Chaudhary


Yes: itertools.combinations

print list(itertools.combinations(w, 2))

You mention this in your question - I'm not sure why you wouldn't look in the docs before asking on StackOverflow.

like image 23
babbageclunk Avatar answered Sep 16 '25 23:09

babbageclunk