aNc@sdZddlmZddlZddlZddlZddlZddlZddlZ ddl Z ddl Z dXej kodYknst dyeeefWn@ek rdefd YZed ed ZZnXyeWnek rd d ZnXyeWnek r>d ZnXyeWnek rcdZnXyeWn#ek rddedZnXyeefWnek r/y#ddlZejejZZWq0eefk r+ddZdYZdefdYZdefdYZq0XnXdZdZ de!fdYZ"dd[dYZ#dZ$dZ%dZ&dZ'd Z(d!Z)d"Z*d#Z+d$Z,d%Z-d&Z.d'Z/d(Z0d)Z1d*Z2d dd+Z3d,Z4d-Z5d.Z6d/Z7dd0Z8d1Z9d2Z:d3Z;d4Z<d5Z=d6Z>d7Z?d8Z@d\d]d^d_gZAeAd9ZBd:ZCd;ZDd<ZEd=ZFd>ZGd?ZHd d@ZIddAZJdBZKdCZLdDZMdEZNddFdGdHZOdIdJZPdIdKZQdLZRdMd`dNYZSdOZTdPeSfdQYZUdReSfdSYZViZWdTZXdUZYedV7ZeeYdW7ZdS(asGProvide some widely useful utilities. Safe for "from utils import *". i(t generatorsNiiisThis code is meant for Python 2.5 through 2.7. You might find that the parts you care about still work in older Pythons or happen to work in newer ones, but you're on your own -- edit utils.py if you want to try it.tboolcBs)eZdZdZdZdZRS(s0Simple implementation of Booleans, as in PEP 285cCs ||_dS(N(tval(tselfR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt__init__scCs|jS(N(R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt__int__scCs d|jS(NtFalsetTrue(sFalsesTrue(R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt__repr__s(t__name__t __module__t__doc__RRR(((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRs  iicCsttj||S(sFSum the elements of seq. >>> sum([1, 2, 3]) 6 (treducetoperatortadd(tseqtstart((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytsum#sccs7d}t|}x||jfV|d7}qdS(sReturn an iterator that enumerates pairs of (i, c[i]). PEP 279. >>> list(enumerate('abc')) [(0, 'a'), (1, 'b'), (2, 'c')] iiN(titertnext(t collectiontitit((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt enumerate,s  ccsTt|drtdnt|}x#|dkrO|d8}||Vq-WdS(s_Iterate over x in reverse order. >>> list(reversed([1,2,3])) [3, 2, 1] tkeyss)mappings do not support reverse iterationiiN(thasattrt TypeErrortlen(RR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytreversed;s   cstj|}rIdkr-tjn|jfdn&dkrb|jn |j|r|jn|S(sYCopy seq and sort and return it. >>> sorted([3, 1, 2]) [1, 2, 3] cs||S(N((txty(tkeytcmp(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytSsN(tcopytNonet __builtins__R tsorttreverse(RR RR&tseq2((RR sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytsortedJs      tBaseSetcBseZdZgdZdZdZdZdZdZdZ dZ d Z d Z d Z d ZeZeZe Ze Ze Ze ZRS( s8set type (see http://docs.python.org/lib/types-set.html)cCs+i|_x|D]}d|j|>> Dict(a=1, b=2, c=3) {'a': 1, 'c': 3, 'b': 2} ((tentries((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytDictst DefaultDictcBs)eZdZdZdZdZRS(s1Dictionary with a default value for unknown keys.cCs ||_dS(N(tdefault(RRY((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCs5||kr|j|S|j|tj|jS(N(tgett setdefaultR"tdeepcopyRY(RR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt __getitem__s cCs t|j}|j||S(N(RXRYRG(RR"((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt__copy__s (R R R RR]R^(((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRXs  tStructcBs)eZdZdZdZdZRS(suCreate an instance with argument=value slots. This is for making a lightweight object whose class doesn't matter.cKs|jj|dS(N(t__dict__RG(RRV((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCs6t|tr"t|j|jSt|j|SdS(N(t isinstanceR_R R`(RR1((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt__cmp__scCsRgt|jD]"\}}d|t|f^q}ddjt|S(Ns%s=%ss Struct(%s)s, (tvarstitemstreprR:R((Rtktvtargs((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRs;(R R R RRbR(((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR_s  cKs3t|tr|j|n|jj||S(sUpdate a dict; or an object with slots; according to entries. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) (RaR*RGR`(RRV((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRG scCsFt|tr|j|dSg|D]}||kr&|^q&SdS(sReturn a copy of seq (or string) with all occurences of item removed. >>> removeall(3, [1, 2, 3, 3, 2, 1, 3]) [1, 2, 2, 1] >>> removeall(4, [1, 2, 3]) [1, 2, 3] tN(RaR<treplace(titemRR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt removeallscCstt|S(sqRemove duplicate elements from seq. Assumes hashable elements. >>> unique([1, 2, 3, 2, 1]) [1, 2, 3] (R5RF(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytunique'scCsttj|dS(sIReturn the product of the numbers. >>> product([1,2,3,4]) 24 i(R R tmul(tnumbers((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytproduct.scsfd}t||dS(sCount the number of elements of seq for which the predicate is true. >>> count_if(callable, [42, None, max, min]) 2 cs|| S(N((tcountR(t predicate(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!:si(R (RrRtf((RrsC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytcount_if5scCs%x|D]}||r|SqWdS(sIf there is an element of seq that satisfies predicate; return it. >>> find_if(callable, [3, min, max]) >>> find_if(callable, [1, 2, 3]) N(R#(RrRR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytfind_if=s  cCs%x|D]}||stSqWtS(sTrue if every element of seq satisfies predicate. >>> every(callable, [min, max]) 1 >>> every(callable, [min, 3]) 0 (RR(RrRR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyteveryGs  cCs+x$|D]}||}|r|SqWtS(sIf some element x of seq satisfies predicate(x), return predicate(x). >>> some(callable, [min, 3]) 1 >>> some(callable, [2, 3]) 0 (R(RrRRtpx((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytsomeRs   cCs%x|D]}||krtSqWtS(sLike (elt in seq), but compares with is, not ==. >>> e = []; isin(e, [1, e, 3]) True >>> isin(e, [1, [], 3]) False (RR(teltRR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytisin^s  cCsS|d}||}x6|D].}||}||kr||}}qqW|S(sReturn an element with lowest fn(seq[i]) score; tie goes to first one. >>> argmin(['one', 'to', 'three'], len) 'to' i((Rtfntbestt best_scoreRtx_score((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytargminqs    cCss||dg}}xU|D]M}||}||krO|g|}}q||kr|j|qqW|S(sReturn a list of elements of seq[i] with the lowest fn(seq[i]) scores. >>> argmin_list(['one', 'to', 'three', 'or'], len) ['to', 'or'] i(tappend(RR{R}R|RR~((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt argmin_list}s    cCs||d}d}xs|D]k}||}||krQ||}}d}q||kr|d7}tj|dkr|}qqqW|S(sReturn an element with lowest fn(seq[i]) score; break ties at random. Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)ii(trandomt randrange(RR{R}tnRR~R|((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytargmin_random_ties      cst|fdS(sReturn an element with highest fn(seq[i]) score; tie goes to first one. >>> argmax(['one', 'to', 'three'], len) 'three' cs | S(N((R(R{(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!s(R(RR{((R{sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytargmaxscst|fdS(sReturn a list of elements of seq[i] with the highest fn(seq[i]) scores. >>> argmax_list(['one', 'three', 'seven'], len) ['three', 'seven'] cs | S(N((R(R{(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!s(R(RR{((R{sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt argmax_listscst|fdS(sFReturn an element with highest fn(seq[i]) score; break ties at random.cs | S(N((R(R{(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!s(R(RR{((R{sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytargmax_random_tiescCs|rt||}ni}x(|D] }|j|dd||>> log2(1024) 10.0 i(tmathtlog10(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytlog2scCst|ddddS(sYReturn the most common value in the list of values. >>> mode([1, 2, 3, 2]) 2 Rii(R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCst|}t|}|ddkr4||dS||dd|dd!}yt|SWntk r|tj|SXdS(sReturn the middle value, when the values are sorted. If there are an odd number of elements, try to average the middle two. If they can't be averaged (e.g. they are strings), choose one at random. >>> median([10, 100, 11]) 11 >>> median([1, 2, 3, 4]) 2.5 iiN(RR(tmeanRRtchoice(RRtmiddle2((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytmedians    cCst|tt|S(s,Return the arithmetic average of the values.(RtfloatR(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCsW|dkrt|}ntjtg|D]}||d^q+t|dS(sWThe standard deviation of a set of values. Pass in the mean if you already know it.iiN(R#RRtsqrtRR(RtmeanvalR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytstddevs cCs0tgt||D]\}}||^qS(s{Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230 (Rtzip(tXtYRR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt dotproductscCstttj||S(s[Component-wise addition of two vectors. >>> vector_add((0, 1), (8, 9)) (8, 10) (ttupleR;R R(tatb((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt vector_addscCs|tjddkS(sReturn true with probability p.gg?(Rtuniform(tp((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt probabilityscCs/t||}gt|D]}|^qS(sPick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.(tweighted_samplertrange(RtweightsRtsamplets((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt weighted_sample_with_replacementscsHgx/|D]'}jr-|dn|q WfdS(sHReturn a random-sample function that picks from seq weighted by weights.ics$tjtjddS(Nii(tbisectRR((Rttotals(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!s(R(RRtw((RRsC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRs %cCset|r|Syt|SWn@tk r`yt|SWqatk r\t|jSXnXdS(sThe argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x' N(tisnumbertintt ValueErrorRR<tstrip(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt num_or_strs   cCs-tt|}g|D]}||^qS(sqMultiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25] (RR(RottotalR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt normalizescCst|t||S(stReturn x clipped to the range [lowest..highest]. >>> [clip(x, 0, 1) for x in [-1, 0.5, 10]] [0, 0.5, 1] (tmaxtmin(Rtlowestthighest((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytclipscCs||j||t|S(N(tindexR(theadingtinctheadings((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt turn_heading,scCs t|dS(Ni(R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt turn_right/scCst|d S(Ni(R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt turn_left2scCs0|\}}|\}}tj||||S(s'The distance between two (x, y) points.(Rthypot(t.0t.1taxtaytbxtby((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytdistance5scCs0|\}}|\}}||d||dS(s5The square of the distance between two (x, y) points.i((RRRRRR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt distance29scCst|tt|||S(sReturn vector, except if any element is less than the corresponding value of lowest or more than the corresponding value of highest, clip to those values. >>> vector_clip((-1, 10), (0, 0), (9, 9)) (0, 9) (R4R;R(tvectorRR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt vector_clip=scs<tjjttfdfdS(sFormat args with the first argument as format string, and write. Return the last arg, or format itself if there are no args.csdS(Ni(((Rh(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!MscsS(N(((tformat(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!Ms(tsyststdouttwriteR<tif_(RRh((RhRsC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytprintfIscCs'ddl}|j|j|dS(sReturn the name of the calling function n levels up in the frame stack. >>> caller(0) 'caller' >>> def f(): ... return caller() >>> f() 'f' iNi(tinspecttgetouterframest currentframe(RR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytcallerOs cs:rfdnfdi_S(sMemoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary.csCt|rt|S||}t|||SdS(N(Rtgetattrtsetattr(tobjRhR(tslotR{(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt memoized_fn`s  cs3jj|s(|j|>> if_(2 + 2 == 4, 'ok', lambda: expensive_computation()) 'ok' N(tcallable(ttesttresultt alternative((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRos  cCsLt|ddpKt|ddpKtt|ddddpKt|S(s0Try to find some reasonable name for the object.tnameiR t __class__(RR<(tobject((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR~s$cCs t|dS(s7Is x a number? We say it is if it has a __int__ method.R(R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCs t|dS(s=Is x a sequence? We say it is if it has a __getitem__ method.R](R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt issequencess s%gc s g|dD]ttdd^q }|rE|g|}ng|D]F}g|D]3ttfdfd^qY^qL}d}t|tg|D]}tt|^q}x2|D]*}|jdt|||DGHqWdS( s?Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. '%6.2f'. (If you want different formats in different columns, don't use print_table.) sep is the separator between columns.itrjusttljustcsS(N(((Rtnumfmt(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!scsS(N(((R(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!scSsttt|S(N(RR;R(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!scss3|])\}}}tt|||VqdS(N(RR<(RtjtsizeR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pys sN(RRR;RR<R:(ttabletheadertsepRtjuststrowtmaxlentsizes((RRsC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt print_tables/P 1  trcCsDddl}tjj|j}tttjj|g||S(s-Open a file based at the AIMA root directory.iN(tutilstostpathtdirnamet__file__topentapplyR:(t componentsRRtdir((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytAIMAFiles cCstdd|g|S(s*Return a file in the AIMA /data directory.s..tdata(R(RR((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytDataFilescCs tdS(s5Use this as a stub for not-yet-implemented functions.N(tNotImplementedError(((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt unimplementedstQueuecBs eZdZdZdZRS(sQueue is an abstract class/interface. There are three types: Stack(): A Last In First Out Queue. FIFOQueue(): A First In First Out Queue. PriorityQueue(order, f): Queue in sorted order (default min-first). Each type supports the following methods and functions: q.append(item) -- add an item to the queue q.extend(items) -- equivalent to: for item in items: q.append(item) q.pop() -- return the top item from the queue len(q) -- number of items in q (also q.__len()) item in q -- does q contain item? Note that isinstance(Stack(), Queue) is false, because we implement stacks as lists. If Python ever gets interfaces, Queue will be an interface.cCstdS(N(tabstract(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCs"x|D]}|j|qWdS(N(R(RRdRk((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytextends (R R R RR(((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRs  cCsgS(s<Return an empty list, suitable as a Last-In-First-Out Queue.((((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytStackst FIFOQueuecBsDeZdZdZdZdZdZdZdZRS(sA First-In-First-Out Queue.cCsg|_d|_dS(Ni(tAR(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRs cCs|jj|dS(N(RR(RRk((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCst|j|jS(N(RRR(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR-scCs|jj|dS(N(RR(RRd((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCsm|j|j}|jd7_|jdkri|jt|jdkri|j|j|_d|_n|S(Niiii(RRR(RR,((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRPs + cCs||j|jkS(N(RR(RRk((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR0s( R R R RRR-RRPR0(((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRs     t PriorityQueuecBsVeZdZeddZdZdZdZdZdZ dZ RS( sA queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is min, the item with minimum f(x) is returned first; if order is max, then it is the item with maximum f(x). Also supports dict-like lookup.cCs|S(N((R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!scCs t|dgd|d|dS(NRtorderRs(RG(RRRs((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCs&tj|j|j||fdS(N(RtinsortRRs(RRk((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRscCs t|jS(N(RR(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR-scCs8|jtkr#|jjddS|jjdSdS(Nii(RRRRP(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRPscstfd|jS(Ncs|\}}|kS(N((Rt_R(Rk(sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR!s(RxR(RRk((RksC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR0scCs.x'|jD]\}}||kr |Sq WdS(N(R(RRR Rk((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyR]s cCsJxCt|jD]2\}\}}||kr|jj|dSqWdS(N(RRRP(RRRtvalueRk((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt __delitem__s" ( R R R RRRR-RPR0R]R (((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyRs     cCsddS(N(R#(R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytignorescCs1d}tjd|}djt||S(s}Some functions are stochastic. We want to be able to write a test with random output. We do that by ignoring the output.cSs$d|krd|Sd|dSdS(Ns = s>>> s >>> ignore(t)((R((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pytfixups s>>> (.*)s (tretfindallR:R;(ttextRttests((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyt random_testss s >>> d = DefaultDict(0) >>> d['x'] += 1 >>> d['x'] 1 >>> d = DefaultDict([]) >>> d['x'] += [1] >>> d['y'] += [2] >>> d['x'] [1] >>> s = Struct(a=1, b=2) >>> s.a 1 >>> s.a = 3 >>> s Struct(a=3, b=2) >>> def is_even(x): ... return x % 2 == 0 >>> sorted([1, 2, -3]) [-3, 1, 2] >>> sorted(range(10), key=is_even) [1, 3, 5, 7, 9, 0, 2, 4, 6, 8] >>> sorted(range(10), lambda x,y: y-x) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> removeall(4, []) [] >>> removeall('s', 'This is a test. Was a test.') 'Thi i a tet. Wa a tet.' >>> removeall('s', 'Something') 'Something' >>> removeall('s', '') '' >>> list(reversed([])) [] >>> count_if(is_even, [1, 2, 3, 4]) 2 >>> count_if(is_even, []) 0 >>> argmax([1], lambda x: x*x) 1 >>> argmin([1], lambda x: x*x) 1 # Test of memoize with slots in structures >>> countries = [Struct(name='united states'), Struct(name='canada')] # Pretend that 'gnp' was some big hairy operation: >>> def gnp(country): ... print 'calculating gnp ...' ... return len(country.name) * 1e10 >>> gnp = memoize(gnp, '_gnp') >>> map(gnp, countries) calculating gnp ... calculating gnp ... [130000000000.0, 60000000000.0] >>> countries [Struct(_gnp=130000000000.0, name='united states'), Struct(_gnp=60000000000.0, name='canada')] # This time we avoid re-doing the calculation >>> map(gnp, countries) [130000000000.0, 60000000000.0] # Test Queues: >>> nums = [1, 8, 2, 7, 5, 6, -99, 99, 4, 3, 0] >>> def qtest(q): ... q.extend(nums) ... for num in nums: assert num in q ... assert 42 not in q ... return [q.pop() for i in range(len(q))] >>> qtest(Stack()) [0, 3, 4, 99, -99, 6, 5, 7, 2, 8, 1] >>> qtest(FIFOQueue()) [1, 8, 2, 7, 5, 6, -99, 99, 4, 3, 0] >>> qtest(PriorityQueue(min)) [-99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 99] >>> qtest(PriorityQueue(max)) [99, 8, 7, 6, 5, 4, 3, 2, 1, 0, -99] >>> qtest(PriorityQueue(min, abs)) [0, 1, 2, 3, 4, 5, 6, 7, 8, -99, 99] >>> qtest(PriorityQueue(max, abs)) [99, -99, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> vals = [100, 110, 160, 200, 160, 110, 200, 200, 220] >>> histogram(vals) [(100, 1), (110, 2), (160, 2), (200, 3), (220, 1)] >>> histogram(vals, 1) [(200, 3), (160, 2), (110, 2), (220, 1), (100, 1)] >>> histogram(vals, 1, lambda v: round(v, -2)) [(200.0, 6), (100.0, 3)] >>> log2(1.0) 0.0 >>> def fib(n): ... return (n<=1 and 1) or (fib(n-1) + fib(n-2)) >>> fib(9) 55 # Now we make it faster: >>> fib = memoize(fib) >>> fib(9) 55 >>> q = Stack() >>> q.append(1) >>> q.append(2) >>> q.pop(), q.pop() (2, 1) >>> q = FIFOQueue() >>> q.append(1) >>> q.append(2) >>> q.pop(), q.pop() (1, 2) >>> abc = set('abc') >>> bcd = set('bcd') >>> 'a' in abc True >>> 'a' in bcd False >>> list(abc.intersection(bcd)) ['c', 'b'] >>> list(abc.union(bcd)) ['a', 'c', 'b', 'd'] ## From "What's new in Python 2.4", but I added calls to sl >>> def sl(x): ... return sorted(list(x)) >>> a = set('abracadabra') # form a set from a string >>> 'z' in a # fast membership testing False >>> sl(a) # unique letters in a ['a', 'b', 'c', 'd', 'r'] >>> b = set('alacazam') # form a second set >>> sl(a - b) # letters in a but not in b ['b', 'd', 'r'] >>> sl(a | b) # letters in either a or b ['a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'] >>> sl(a & b) # letters in both a and b ['a', 'c'] >>> sl(a ^ b) # letters in a or b but not both ['b', 'd', 'l', 'm', 'r', 'z'] >>> a.add('z') # add a new element >>> a.update('wxy') # add multiple new elements >>> sl(a) ['a', 'b', 'c', 'd', 'r', 'w', 'x', 'y', 'z'] >>> a.remove('x') # take one element out >>> sl(a) ['a', 'b', 'c', 'd', 'r', 'w', 'y', 'z'] >>> weighted_sample_with_replacement([], [], 0) [] >>> weighted_sample_with_replacement('a', [3], 2) ['a', 'a'] >>> weighted_sample_with_replacement('ab', [0, 3], 3) ['b', 'b', 'b'] sX >>> weighted_sample_with_replacement(range(10), [x*x for x in range(10)], 3) [8, 9, 6] (ii(i(((ii(ii(ii(ii((ZR t __future__RR RRR"Rtos.pathRRRt version_infotAssertionErrorRRRt NameErrorRRRRR(R#RFRCtsetstSett ImmutableSett ImportErrorR)tinfinityRWR*RXR_RGRlRmRpRtRuRvRxRzRRRRRRRRRRRRRRRRRRRRt orientationsRRRRRRRRRRRRRRRRRRRRRtFigR R(((sC:\Users\\Desktop\ 2011-12\ \\2\2_ \ \Problem2_1\utils.pyts`"          ; 7