Python equivalent for Ruby combination method

Harsh Trivedi

Is there idiomatic python way to list all combinations of specific size from a list?

The following code works in ruby (here), I wonder if there is python equivalent for this:

a = [1, 2, 3, 4]
a.combination(1).to_a  #=> [[1],[2],[3],[4]]
a.combination(2).to_a  #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]

PS: I am not looking for permutations, but combinations of specific size.

Thanks a lot : )

karthikr

The itertools module has a combinations method which does this for you.

itertools.combinations(a, len)

Demo:

>>> a = [1, 2, 3, 4]
>>> import itertools
>>> itertools.combinations(a, 2)
<itertools.combinations object at 0x109c276d8>
>>> list(itertools.combinations(a, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
>>> list(itertools.combinations(a, 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>> list(itertools.combinations(a, 4))
[(1, 2, 3, 4)]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Is there a python equivalent to the ruby inspect method?

From Dev

Is there a python equivalent to the ruby inspect method?

From Dev

Python equivalent to Ruby Array.each method

From Dev

Ruby's Array Combination Method

From Dev

is there an equivalent of the ruby any method in javascript?

From Dev

Python Equivalent to Ruby 'is_a?'

From Dev

Python magic * or ** method equivalent

From Dev

Python equivalent of a ruby Gem file

From Dev

Python's equivalent of Ruby's ||=

From Dev

Ruby equivalent for Python's "try"?

From Dev

shortest ruby equivalent of this Python Snippet

From Dev

Python equivalent of Ruby's .select

From Dev

shortest ruby equivalent of this Python Snippet

From Dev

Equivalent ruby load function in python

From Dev

Python to Ruby Conversion, stuck on the equivalent

From Dev

Is there a ruby equivalent to the php __invoke magic method?

From Dev

Does an equivalent to prepend method exist in ruby 1.9.3?

From Dev

Is there a Clojure equivalent of Ruby's #tap method

From Dev

Ruby string interpolation equivalent to python's .format()

From Java

Is there a Python equivalent to Ruby's string interpolation?

From Dev

What's the Ruby equivalent of Python's defaultdict?

From Dev

Python equivalent of Ruby's each_with_index?

From Dev

ruby equivalent of python izip_longest

From Dev

Ruby hash equivalent to Python dict setdefault

From Dev

What is the Ruby equivalent of the Python max() function?

From Dev

Equivalent of Python's min() with lambda in Ruby

From Dev

What would the ruby equivalent be to this python script?

From Dev

What's the equivalent of this Ruby code in Python?

From Dev

Equivalent of Ruby's Enumerable#each_slice method in FSharp

Related Related

HotTag

Archive