Peter Norvig, the famous American computer scientist and Director of Research at Google Inc., participated in this year’s Advent of Code (a series of small programming puzzles), and shared his experience in an interesting blog post.
The post starts with this amazing collection of Python utility functions, which may also be useful for your next project:
# Python 3.ximportreimportnumpyasnpimportmathimporturllib.requestfromcollectionsimportCounter,defaultdict,namedtuple,dequefromfunctoolsimportlru_cachefromitertoolsimportpermutations,combinations,chain,cycle,productfromheapqimportheappop,heappushdefInput(day):"Open this day's input file."filename='advent2016/input{}.txt'.format(day)try:returnopen(filename)exceptFileNotFoundError:urllib.request.urlopen("http://norvig.com/ipython/"+filename)deftranspose(matrix):returnzip(*matrix)deffirst(iterable):returnnext(iter(iterable))deffirsttrue(iterable):returnfirst(itforitiniterableifit)defcounttrue(iterable):returnsum(bool(it)foritiniterable)cat=''.joinØ=frozenset()# Empty setinf=float('inf')BIG=10**999defgrep(pattern,lines):"Print lines that match pattern."forlineinlines:ifre.search(pattern,line):print(line)defgroupby(iterable,key=lambdait:it):"Return a dic whose keys are key(it) and whose values are all the elements of iterable with that key."dic=defaultdict(list)foritiniterable:dic[key(it)].append(it)returndicdefpowerset(iterable):"Yield all subsets of items."items=list(iterable)forrinrange(len(items)+1):forcincombinations(items,r):yieldc# 2-D points implemented using (x, y) tuplesdefX(point):returnpoint[0]defY(point):returnpoint[1]defneighbors4(point):"The four neighbors (without diagonals)."x,y=pointreturn((x+1,y),(x-1,y),(x,y+1),(x,y-1))defneighbors8(point):"The eight neifhbors (with diagonals)."x,y=pointreturn((x+1,y),(x-1,y),(x,y+1),(x,y-1),(X+1,y+1),(x-1,y-1),(x+1,y-1),(x-1,y+1))defcityblock_distance(p,q=(0,0)):"City block distance between two points."returnabs(X(p)-X(q))+abs(Y(p)-Y(q))defeuclidean_distance(p,q=(0,0)):"Euclidean (hypotenuse) distance between two points."returnmath.hypot(X(p)-X(q),Y(p)-Y(q))deftrace1(f):"Print a trace of the input and output of a function on one line."deftraced_f(*args):result=f(*args)print('{} = {}'.format(_callstr(f,args),result))returnresultreturntraced_fdeftrace(f):"Print a trace of the call and args on one line, and the return on another."deftraced_f(*args):print(_callstr(f,args))trace.indent+=1try:result=f(*args)finally:trace.indent-=1print('{} = {}'.format(_callstr(f,args),result))returnresultreturntraced_ftrace.indent=0def_callstr(f,args):"Return a string representing f(*args)."return'{}{}({})'.format('> '*trace.indent,f.__name__,', '.join(map(str,args)))defastar_search(start,h_func,move_func):"Find a shortest sequence of states from start to a goal state (a state s with h_func(s) == 0)."frontier=[(h_func(start),start)]# A priority queue, ordered by path length, f = g + hprevious={start:None}# start state has no previous state; other states willpath_cost={start:0}# The cost of the best path to a state.whilefrontier:(f,s)=heappop(frontier)ifh_func(s)==0:returnPath(previous,s)fors2inmove_func(s):new_cost=path_cost[s]+1ifs2notinpath_costornew_cost<path_cost[s2]:heappush(frontier,(new_cost+h_func(s2),s2))path_cost[s2]=new_costprevious[s2]=sreturndict(fail=True,front=len(frontier),prev=len(previous))defPath(previous,s):"Return a list of states that lead to state s, according to the previous dict."return([]if(sisNone)elsePath(previous,previous[s])+[s])
Read the full post for more interesting ideas and elegant solutions.