PDA

View Full Version : Python combinations in list



n~kf)}BW%
January 16th, 2011, 01:31 AM
I would like to create a function that works as followed:


list = ['apple','banana','lemon','orange']

def combos(list, number):
...

combos(list,2)
['apple','banana'],['apple','lemon'],['apple','orange'],['banana','orange'],['banana','lemon'],['lemon','orange']

combos(list,1)
['apple'],['banana'],['lemon'],['orange']

Please help me figure it out :) Thanks!

PS: What is this even called? It's not Cartesian product...

schauerlich
January 16th, 2011, 05:58 AM
itertools.combinations() (http://docs.python.org/library/itertools.html#itertools.combinations)

CptPicard
January 16th, 2011, 10:24 AM
http://ubuntuforums.org/showthread.php?t=649295&highlight=combinations

unknownPoster
January 16th, 2011, 11:20 AM
Seriously, the first link in the Google search for "Python List Combinations" gives you exactly what you want. If you want to get help here, you need to put in some work yourself.

wmcbrine
January 16th, 2011, 09:35 PM
PS: What is this even called? It's not Cartesian product...Combinatorics. (http://www.youtube.com/watch?v=w0i_ZFlGTVY)

n~kf)}BW%
January 16th, 2011, 09:59 PM
Seriously, the first link in the Google search for "Python List Combinations" gives you exactly what you want. If you want to get help here, you need to put in some work yourself.

Hey man, you got me wrong... I want to do this myself. I don't like to include itertools for just one call in my whole program...

Thanks for the help people, anyway...

ziekfiguur
January 16th, 2011, 10:50 PM
I don't like to include itertools for just one call in my whole program...

Why not use

from itertools import combinations

ziekfiguur
January 16th, 2011, 10:56 PM
sorry

wmcbrine
January 17th, 2011, 08:30 AM
I don't like to include itertools for just one call in my whole program...If it's just one call, it makes more sense to import it, rather than devoting a bunch of code to it. Importing it isn't that much overhead. The only reason I might avoid it would be to maintain compatibility with Python < 2.6.

Anyway, check out the implementation linked in #2 -- that's what you'd have to do instead.

n~kf)}BW%
February 3rd, 2011, 12:39 AM
Thank you :) You have both been helpful. I'll import combinations from itertools. Didn't know you could do it that way