utils

Slice to Range

Sometimes inside __getitem__() method you may need to convert the “slice” coming as argument to a “range” :

#convert slice to range
def slice2range(s):	
	start = 0 if s.start is None else s.start
	step = 1 if s.step is None else s.step
	end = step if s.stop is None else s.stop
	return range(start,end,step)

#inside your code it will be something like this :
def __getitem__(self, item):
        if isinstance(item, slice):
        ....

Example :

: slice2range(slice(2,5))                                                                                                                                            
: range(2, 5)

: slice2range(slice(2,5,1))                                                                                                                                          
: range(2, 5)

: slice2range(slice(5))                                                                                                                                              
: range(0, 5)

Java : join()

Join list of strings :

//joins Iterable or Collection into a String
public static <T> String join(String delimiter, Iterable<T> lst) {
	StringBuilder str = new StringBuilder();
	Iterator<T> it = lst.iterator();
	while ( it.hasNext() ) {
		str.append(it.next().toString());
		if (it.hasNext()) str.append(delimiter);
	}
	return str.toString();
}

Java invention of the decade

Ladies and gentleman,
I present to you the biggest invention in Java since sliced bread :

public static <ARG> void say(ARG arg) { System.out.println(arg); }

Now you can do :

say("This is less annoying than System.out.whatever"; }

… where is my award :”)

Chunker

Given a List, iterator or a Range yield the result in chunks of items

#returns lazily an iterator,range,list in chunks 
def chunker(it,size):
	rv = []	
	for i,el in enumerate(it,1) :	
		rv.append(el)
		if i % size == 0 : 
			yield rv
			rv = []
	if rv : yield rv		

Example :

: list(chunker(range(0,10),3))                                                                                                                                       
: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

: [ sum(x) for x in chunker(range(0,10),3) ]                                                                                                                         
: [3, 12, 21, 9]

zip function in Prolog

:- use_module(library(lambda)). 
zip1(L1,L2,Z) :- scanl(\X^Y^_^[X,Y]^[X,Y],L1,L2,_,[_|Z]). 
zip2(L1,L2,Z) :- maplist(\X^Y^[X,Y]^[X,Y],L1,L2,Z). 

or better this one :

pair(X,Y,[X,Y]).
zip(L1,L2,Z) :- maplist(pair,L1,L2,Z).

?- zip([1,2,3],[4,5,6],Z).
Z = [[1, 4], [2, 5], [3, 6]].