Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the Ruby equivalent of Python itertools, esp. combinations/permutations/groupby?

Python's itertools module provides a lots of goodies with respect to processing an iterable/iterator by use of generators. For example,

permutations(range(3)) --> 012 021 102 120 201 210

combinations('ABCD', 2) --> AB AC AD BC BD CD

[list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D

What are the equivalent in Ruby?

By equivalent, I mean fast and memory efficient (Python's itertools module is written in C).

like image 988
Hai-Anh Trinh Avatar asked Mar 14 '10 18:03

Hai-Anh Trinh


People also ask

What is Itertools Groupby in Python?

groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.

What are the Itertools in Python?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

What is combinations in Itertools?

itertools. combinations (iterable, r) Return r length subsequences of elements from the input iterable. The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

What is Islice in Python?

islice() - The islice() function allows the user to loop through an iterable with a start and stop , and returns a generator. map() - The map() function creates an iterable map object that applies a specified transformation to every element in a chosen iterable.


1 Answers

Array#permutation, Array#combination and Enumerable#group_by are defined in ruby since 1.8.7. If you're using 1.8.6 you can get equivalent methods from facets or active_support or backports.

Example Usage:

[0,1,2].permutation.to_a
#=> [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]

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

[0,0,0,1,1,2].group_by {|x| x}.map {|k,v| v}
#=> [[0, 0, 0], [1, 1], [2]]

[0,1,2,3].group_by {|x| x%2}
#=> {0=>[0, 2], 1=>[1, 3]}
like image 135
sepp2k Avatar answered Oct 29 '22 11:10

sepp2k