Skip to content

Instantly share code, notes, and snippets.

@thecaralice
Last active July 15, 2021 20:32
Show Gist options
  • Save thecaralice/73ea16af26ff8265118b77c0d61275a1 to your computer and use it in GitHub Desktop.
Save thecaralice/73ea16af26ff8265118b77c0d61275a1 to your computer and use it in GitHub Desktop.
Useful snippets
import itertools as it
def group(iterable, size, fill=None):
yield from it.zip_longest(*[iter(iterable)] * size, fillvalue=fill)
if __name__ == '__main__':
print(*group(range(10), 3, 0), sep=', ') # -> (0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 0, 0)
#include <iostream> // For main
#include <vector> // For main
template <typename T>
struct reversion_wrapper { T& iterable; };
template <typename T>
auto begin(reversion_wrapper<T>& w) { return std::rbegin(w.iterable); }
template <typename T>
auto end(reversion_wrapper<T>& w) { return std::rend(w.iterable); }
template <typename T>
auto rbegin(reversion_wrapper<T>& w) { return std::begin(w.iterable); }
template <typename T>
auto rend(reversion_wrapper<T>& w) { return std::end(w.iterable); }
template <typename T>
reversion_wrapper<T> reverse(T&& iterable) { return { iterable }; }
int main() {
std::vector<int> v {1, 2, 3, 4, 5, 6, 7};
for (auto&& i: v) {
std::cout << i << ' ';
}
std::cout << '\n';
for (auto&& i: reverse(v)) {
std::cout << i << ' ';
}
/*
* Output:
* 1 2 3 4 5 6 7
* 7 6 5 4 3 2 1
*/
}
import itertools as it
def transpose(iterable, fill=None):
yield from it.zip_longest(*iterable, fillvalue=fill)
if __name__ == '__main__':
print(*transpose([
(1, 2, 3),
(4, 5, 6),
(7, 8, 9)
]), sep=', ') # (1, 4, 7),
# (2, 5, 8),
# (3, 6, 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment