# -*- coding: utf-8 -*-
'''
Created on Sep 18, 2010

@author: boban
'''

def window_contexts_generator(tokens, size_left=3, size_right=3):
	"""
	Generator of all contexts for given tokens. Contexts returned are triples:
	(left_context, center, right_context),
	where left_context (right_context) is a lists of tokens occurring to the left (right) of the token
	in center. Size of both contexts are provided by user, but at the beginning (end) of given tokens
	_left (right) contexts are smaller.

	tokens should be list-like type, that supports indexing, slicing and length.
	
	>>> tokens = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
	>>> gen = window_contexts_generator(tokens, 3,2)
	>>> gen.next() 
	([], 'a', ['b', 'c'])
	>>> gen.next()
	(['a'], 'b', ['c', 'd'])
	>>> gen.next()
	(['a', 'b'], 'c', ['d', 'e'])
	>>> gen.next()
	(['a', 'b', 'c'], 'd', ['e', 'f'])
	>>> gen.next() 
	(['b', 'c', 'd'], 'e', ['f', 'g'])
	>>> gen.next()
	(['c', 'd', 'e'], 'f', ['g'])
	>>> gen.next()
	(['d', 'e', 'f'], 'g', [])
	>>> gen.next()
	Traceback (most recent call last):
	...
	StopIteration
	"""
	lentokens = len(tokens)
	for i in xrange(lentokens):
		left = i - size_left
		right = i + size_right+1

		if left < 0: 
			left = 0
		if right > lentokens: 
			right = lentokens

		yield (tokens[left:i], tokens[i], tokens[i+1:right])
		
if __name__ == '__main__':
	import doctest
	doctest.testmod()