Skip to content

Instantly share code, notes, and snippets.

@tiwijo
tiwijo / dowhile.py
Created March 14, 2012 21:16
Do/While in Python
from functools import wraps
import inspect
def first(fn):
'''Wrap a function so True is returned the first time it is called.'''
@wraps(fn)
def wrapper(self, *args, **kwargs):
if self.first:
self.first = False
@tiwijo
tiwijo / inwise.py
Created December 7, 2011 19:51
Iterate over N adjacent elements of a list
from itertools import tee, izip
def inwise(iterable, n=2):
'''Return an iterator over iterable where n adjacent items are returned at
a time.
@param n : int
the number of adjacent items to return'''
iters = tee(iterable, n=n)
@tiwijo
tiwijo / ichunk.py
Created October 12, 2011 19:37
Chunking n adjacent items in a list
#! /usr/bin/env python
from itertools import izip_longest
def ichunk(iterable, n):
'''Chunk n adjacent elements in the iterable. For example
ichunk((1,2,3,4,5,6), 2) -> (1,2),(3,4),(5,6)'''
iters = (iter(iterable),) * n
return izip_longest(*iters, fillvalue=None)