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).
groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.
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.
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.
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.
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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With