123
CCPS 109 Computer Science I Labs Ilkka Kokkarinen Chang School of Continuing Education Ryerson University Version of January 12, 2022

CCPS 109 Computer Science I Labs

  • Upload
    others

  • View
    7

  • Download
    1

Embed Size (px)

Citation preview

CCPS 109 Computer Science I Labs

Ilkka Kokkarinen

Chang School of Continuing Education Ryerson University

Version of January 12, 2022

GeneralrequirementsThis document contains speci0ications for the lab problems in the course CCPS 109 ComputerScience I, as taught by Ilkka Kokkarinen for Chang School of Continuing Education, RyersonUniversity,Toronto,Canada.Itcontains109individualproblems(plus0ivebonusproblems)foryoutochooseyourbattlesfrom.Theproblemsarepresentedroughlyinorderofincreasingcomplexity.

All problems are designed to allow solutions using only the core computation structuresintroducedduringthe<irst<iveweeksofthiscourse,assumingthatthestudenthascompletedenoughpracticeproblemsat theexcellentCodingBatPython interactive training site, oracquiredtheequivalentknowledgefromearlierstudies.Exceptforahandfulofproblemsthatexplicitlypointout the standard librarymodules that are useful to solve them, no knowledge of any specializedPython libraries is required. Despite this, you are allowed to use anything in the Python 3standardlibrarythatyou0indusefulinconstructingyourprogramlogic.Incomputerscienceandallofprogramming,noproblemshouldeverhavetobesolvedtwice!

Eachcorrectlysolvedproblemisworththeexactsameonepointtoyourcoursegrade.Yourgradestartsfromthebaselineof40points,byitselfnotquiteenoughtopassthiscourse.Solvingtenproblems makes your course grade reach 50 points, which corresponds to the lowest possiblepassingcoursegradeofDminus.Solving0iftyproblems(yes,yes,forgrownuprealsies,those0iftyproblemscanbeany0ifty)takesyouupto90pointswherethehighestpossiblegradeofA+awaits.

Youmustimplementallthesefunctionsinasinglesourcecode<ilenamedlabs109.py.Thisallows you to run the tester109.py script at any time to validate the functions you havecompletedsofar,soyoualwaysknowexactlywhereyouarestandingonthiscourse.Thesetestsareexecutedinthesameorderthatyourfunctionsappearinsidethelabs109.py0ile.

Your functionsmay assume that the arguments given to them them are as promised in theproblemspeci<ication,sothatthesefunctionsneverhavetohandleandrecoverfromargumentswhosevalueortypeisinvalid.Yourfunctionsmustespeciallyhandlezerointegersandemptylistscorrectlywhenevertheycanbelegitimateargumentvalues.

The test for each individual function should take atmost a couple of seconds to completewhenexecutedonanoff-the-shelfdesktopfromthepastcoupleofyears.Ifsometesttakesaminuteormoretocomplete,yourcodeistooslowanditslogicdesperatelyneedstobestreamlined.Thisisusuallyachievedbyshavingoffonelevelofnestingfromthestructuredloops,occasionallywiththeaid of aset or adict to remember the stuff that your functionhas seen anddone so far. Theautomatedtesterimposesatwentysecondcutoffforeachtesttocomplete,afterwhichthetest isforcefullyterminated.

Silenceisgolden.Noneofyourfunctionsshouldprintanythingontheconsole,butreturntheexpectedresultsilently.Youcandosomedebuggingoutputsduringthedevelopment,butremembertocommentallofthemoutbeforesubmission.

This speci0ication document and the automated tester are released under GNU Public Licenseversion3sothattheycanbeadaptedanddistributedamongallteachersandstudentsofcomputerscience.Theauthorcompiledtheseproblemsovertimefromagallimaufryofsourcesrangingfromthe original lab and exam problems of his old Java version of this course to a multitude ofprogrammingpuzzleandcodechallengesitessuchasLeetCode,CodeAbbey,StackExchangeCodeGolf, andWolfram Programming Challenges. Classic recreationalmathematics (yes, that is a realthing)columnsbyMartinGardnerandhisspiritualdisciplesalsoinspiredmanyproblems.

Theauthorhas tried tododgenot just theScyllaof thewell-wornproblems that you can 0ind inbasically all textbooks and online problem collections, but also the Charybdis of pointlessmake-workdrudgery thatdoesn’thaveany inherentmeaningorpurposeon itsown,at leastabove theblunt0ingerpracticetoprovidebillable“jobsfortheboys”tomaintaintheillusionthatTheMachineisstillchurningasintended.Someoftheseseeminglysimpleproblemsalsotouchthedeeperissuesof computer science that you will encounter in your later undergraduate and graduate courses.Occasionally these problems even relate to entirely separate 0ields of human endeavour, whichmakesthemhavenontrivialworldviewimplications,bothphilosophicalandpractical.

This problem set also has an of0icial associated subreddit r/ccps109 for students to discuss theindividualproblemsandassociatedissues.Thisdiscussionshouldtakeplaceatthelevelofideas,sothatnosolutioncodeshouldbepostedorrequested.Anyissueswithcoursemanagementandthecourse schedule in any particular semester should be kept out of this subreddit to give a morepermanentandfundamentalnature.Furthermore,nostudentshouldatanytimebestuckwithanyoneproblem.Onceyouembarkonsolvingtheseproblems,youshouldreadaheadto 0indat least0iveproblemsthatinterestyou.Keepthemsimmeringonyourmentalbackburnerasyougoaboutyournormaldays.Thenwhenyougetonanactualkeyboard,workontheproblemwhereyoufeelyourselfbeingclosesttoaworkingsolution.

The author wishes to thank past students Shu Zhu Su, Rimma Konoval,MohammedWaqas,ZhouqinHeandKarelTutsuforgoingaboveandbeyondthecallofdutyinsolvingtheseproblemsinwaysthateitherrevealederrorsintheoriginalproblemspeci0icationsortheinstructor'sprivatemodel solutions, or more fortunately, independently agreed with the instructor's private modelsolution and by doing somassively raised the con0idence to the correctness of both. A legion ofindividualstudentswhopointedoutambiguities,errorsandinconsistenciesinparticularproblemseffectivelyactedasagiantZambonitoplanetheiceforallfuturestudentstoskateoveralittlebiteasier.Members of that horde, you all knowwho you are. All remaining errors, ambiguities andinconsistenciesbothlogicalandextracurricularremainthesoleresponsibilityofIlkkaKokkarinen.Reportanyandallsucherrorsasdiscoveredtoilkka.kokkarinen@gmail.com.

ListofProblems

Ryersonlettergrade 10

Ascendinglist 11

Rif0leshuf0lekerfuf0le 12

Eventheodds 13

Cyclopsnumbers 14

Dominocycle 15

Colourtrio 16

Countdominators 17

Beattheprevious 18

Subsequentwords 19

Taxiℤumℤum 20

Exactchangeonly 21

Rooksonarampage 22

Tryaspatula 23

Wordswithgivenshape 24

Chirality 25

Thecardthatwinsthetrick 26

Doyoureachmany,doyoureachone? 27

Sevensrule,zerosdrool 28

Fulcrum 29

Failwhiledaringgreatly 30

Allyourfractionsarebelongtobase 31

Recaman'ssequence 32

Counttheballsoffthebrassmonkey 33

Countgrowlers 34

Bulgariansolitaire 35

ScyllaorCharybdis? 36

Longestarithmeticprogression 37

Bestoneoutofthree 38

Collectingnumbers 39

CountTroikanoff,Ipresume 40

Crackthecrag 41

Threesummersago 42

Sumoftwosquares 43

CarryonPythonista 44

Asbelow,soabove 45

Expandpositiveintegerintervals 46

Collapsepositiveintegerintervals 47

Prominentlyfeatured 48

Likeakidinacandystore,exceptwithoutmoney 49

Dibstodubs 50

Nearestsmallerelement 51

Interesting,intersecting 52

Soshallyousow 53

That'senoughofyou! 54

Brussel'schoice 55

Corneredcases 56

Countconsecutivesummers 57

McCulloch'ssecondmachine 58

That'senoughforyou! 59

Crabbucketlist 60

Whatdoyouhear,whatdoyousay? 61

Bishopsonabinge 62

Dem’ssomemightytallwords,pardner 63

Upforthecount 64

Revorsethevewels 65

Everybodyonthe0loor,comedotheScroogeShuf0le 66

Rationallinesofaction 67

Verbosregulares 68

Hippityhoppity,abolishloopity 69

Wherenoonecanhearyoubounce 70

Nearestpolygonalnumber 71

Don’tworry,wewill0ixitinthepost 72

Fractraninterpreter 73

Permutationcycles 74

Whoevermustplay,cannotplay 75

ztallocecneuqes 76

Thesolutionsolution 77

Reverseascendingsublists 78

Brangelin-o-maticforthepeople 79

Linewithmostpoints 80

Omnomnom 81

Autocorrectforsausage0ingers 82

Uambcsrlnethewrod 83

Substitutionwords 84

Manhattanskyline 85

Countoverlappingdisks 86

Ordinarycardinals 87

Countdivisiblesinrange 88

Bridgehandshape 89

MiltonWorkpointcount 90

Neverthetwainshallmeet 91

Bridgehandshorthandform 92

Points,schmoints 93

Bullsandcows 94

Frequencysort 95

Callingallunits,B-and-Einprogress 96

Lunaticmultiplication 97

Distributionofabstractbridgehandshapes 98

Fibonaccisum 99

Wythoffarray 100

Rookswithfriends 101

PossiblewordsinHangman 102

AllbranchesleadtoRome 103

Bethereorbesquare 104

Flipoftime 105

Bulgariancycle 106

Squareitoutamongstyourselves 107

Sumofdistinctcubes 108

Countmaximallayers 109

Maximumcheckerscapture 110

Collatzydistance 111

VanEcksequence 112

Tipsandtrips 113

Balancedternary 114

LordsofMidnight 115

Optimalcragscore 116

Paintedintoacorner 117

GofortheGrand:In0initeFibonacciword 118

Bonusproblem110:ReversetheRule110 119

Bonusproblem111:Aye,eye,I 120

Bonusproblem112:Countdominotilings 121

Bonusproblem113:Invadersmustdie 122

Bonusproblem114:Steppingstones 123

Ryerson letter grade

def ryerson_letter_grade(pct):

Giventhepercentagegrade,calculateandreturnthelettergradethatwouldappearintheRyersongradestranscript,asde0inedonthepageRyersonGradeScales.Thislettergradeshouldbereturnedasastringthatconsistsoftheuppercaseletterfollowedbythemodi0ier'+'or'-',ifthereisone.Thisfunctionshouldworkcorrectlyforallvaluesofpctfrom0to150.

Same as all other programming problems that follow this problem, this can be solved in variousdifferentways.Thesimplestwaytosolvethisproblemwouldprobablybetouseanif-elseladder.The0ilelabs109.pygivenintherepositoryikokkari/PythonProblemsalreadycontainsanimplementation of this function for you to run the tester script tester109.py to verify thateverythingishunkydory.

AsyoulearnmorePythonandtechniquestomakeitdanceforyou,youmaythinkupotherwaystosolve this problem. Some of these would be appropriate for actual productive tasks done in aprofessional coding environment, whereas others are intended to be taken in jest as a kind ofconceptualperformanceart.Apopulargenreofrecreationalpuzzlesinallprogramminglanguagesis to solve some straightforward problem with an algorithmic equivalent of a needlesslycomplicatedRubeGoldbergmachine,todemonstratetheuniversalityandunityofallcomputation.

pct Expectedresult

45 'F'

62 'C-'

89 'A'

107 'A+'

Ascending list

def is_ascending(items):

Determinewhetherthesequenceofitems isstrictlyascending sothateachelement isstrictlylarger (not just merely equal to) than the element that precedes it. ReturnTrue if the list ofitemsisstrictlyascending,andreturnFalseotherwise.

Notethattheemptysequenceisascending,asisalsoeveryone-elementsequence,sobecarefulthatyour function returns the correct answers in these seemingly insigni0icant edge cases of thisproblem. (If thesesequenceswerenotascending,pray tell,whatwouldbe the twoelements thatviolatetherequirementandmakethatparticularsequencenotbeascending?)

Inthesamespirit,notehoweverypossibleuniversalclaimmadeabouttheelementsofanemptysequenceistriviallytrue!Forexample,ifitemsistheemptysequence,thetwoclaims“Allelementsofitemsareodd”and“Allelementsofitemsareeven”arebothequallytrue,asisalsotheclaim“Allelementsofitemsarecolourlessgreenideasthatsleepfuriously.”

items Expectedresult

[] True

[-5, 10, 99, 123456] True

[2, 3, 3, 4, 5] False

[-99] True

[4, 5, 6, 7, 3, 7, 9] False

[1, 1, 1, 1] False

Riffle shuffle kerfuffle

def riffle(items, out=True):

Givenalistofitems whoselengthisguaranteedtobeeven(notethat“oddly”enough,zeroisanevennumber), create and return a list producedbyperforming aperfectrif<le to theitems byinterleavingtheitemsofthetwohalvesofthelistinanalternatingfashion.

Whenperformingaperfectrif0leshuf0le,alsoknownastheFaroshuf0le,thelistofitemsissplitintwoequalsizedhalves,eitherconceptuallyorinactuality.The0irsttwoelementsoftheresultarethenthe0irstelementsofthosehalves.Thenexttwoelementsoftheresultarethesecondelementsofthosehalves,followedbythethirdelementsofthosehalves,andsoonuptothelastelementsofthosehalves.Theparameteroutdetermineswhetherthisfunctionperformsanoutshuf0leoraninshuf0lethatdetermineswhichhalfofthedeckthealternatingcardis0irsttakenfrom.

items out Expectedresult

[1, 2, 3, 4, 5, 6, 7, 8] True [1, 5, 2, 6, 3, 7, 4, 8]

[1, 2, 3, 4, 5, 6, 7, 8] False [5, 1, 6, 2, 7, 3, 8, 4]

[] True []

['bob', 'jack'] True ['bob', 'jack']

['bob', 'jack'] False ['jack', 'bob']

Even the odds

def only_odd_digits(n):

Checkthatthegivenpositiveintegerncontainsonlyodddigits(1,3,5,7and9)whenitiswrittenout.ReturnTrue if this is the case, andFalse otherwise.Note that thisquestion isnot askingwhetherthenumbernitselfisoddoreven.Youthereforewillhavetolookateverydigitofthegivennumberbeforeyoucanproclaimthatthenumbercontainsnoodddigits.

Toextractthelowestdigitofapositiveintegern,usetheexpressionn%10.Tochopoffthelowestdigitandkeeptherestofthedigits,usetheexpressionn//10.Or,ifyoudon'twanttobethisfancy,youcan0irstconvertthenumberintoastringandworkfromtherewithstringoperations.

n Expectedresult

8 False

1357975313579 True

42 False

71358 False

0 False

Cyclops numbers

def is_cyclops(n):

Anonnegativeintegerissaidtobeacyclopsnumberifitconsistsofanoddnumberofdigitssothat themiddle(morepoetically, the“eye”)digit isazero,andallotherdigitsof thatnumberarenonzero.Thisfunctionshoulddeterminewhetheritsparameterintegernisacyclopsnumber,andreturneitherTrueorFalseaccordingly.

As an extra challenge, you can try to solve this problemusingonly loops, conditions and integerarithmetic operations,without 0irst converting the integer into a string andworking from there.Dividinganintegerby10withtheintegerdivision//effectivelychopsoffitslastdigit,whereastheremainder operator% can be used to extract that last digit. These operations allowus to iteratethroughthedigitsofanintegeroneatthetimefromlowesttohighest,almostasifthatintegerweresomekindoflazysequenceofdigits.

Evenbetter,thisoperationdoesn'tworkmerelyforthefamiliarbaseten,butitworksforanybasebyusing thatbaseas thedivisor.Especiallyusing twoas thedivisor insteadof tenallowsyou toiterate through thebits of thebinary representation of any integer,whichwill come handy inproblems inyour latercourses thatexpectyou tobeable tomanipulate these individualbits. (Inpractice thesedivisionandremainderoperationsareoften furthercondensed intoequivalentbutfasterbitshiftandbitwiseandoperations.)

n Expectedresult

0 True

101 True

98053 True

777888999 False

1056 False

675409820 False

Domino cycle

def domino_cycle(tiles):

Asingledominotileisrepresentedasatwo-tupleofitspipvalues,suchas(2,5)or(6,6).Thisfunctionshoulddeterminewhetherthegivenlistoftilesformsacyclesothateachtileinthelistendswiththeexactsamepipvaluethatitssuccessortilestartswith,thesuccessorofthelasttilebeingthe0irsttileofthelistsincethisissupposedtobeacycleinsteadofachain.ReturnTrue ifthegivenlistoftilesformssuchacycle,andFalseotherwise.

tiles Expectedresult

[(3, 5), (5, 2), (2, 3)] True

[(4, 4)] True

[] True

[(2, 6)] False

[(5, 2), (2, 3), (4, 5)] False

[(4, 3), (3, 1)] False

Colour trio

def colour_trio(colours):

This problem was inspired by the Mathologer video “Secret of Row 10”. To start, assume theexistenceof three values called “red”, “yellow” and “blue”. Thesenames serve as colourful (heh)mnemonicsandcouldaswellhavebeen0,1,and2,or“foo”,“bar”and“baz”;noconnectiontoactualphysicalcoloursis implied.Next,de0inearuletomixsuchcolourssothatmixinganycolourwithitselfgivesthatsamecolour,whereasmixinganytwodifferentcoloursalwaysgivesthethirdcolour.For example,mixing blue to blue gives that same blue,whereasmixing blue to yellow gives red,sameasmixingyellowtoblue,orredtored.

Giventhe0irstrowofcolours asastringoflowercaseletters,thisfunctionshouldconstructtherowsbelowthe0irstrowonerowatthetimeaccordingtothefollowingdiscipline.Eachrowisoneelementshorterthanthepreviousrow.Thei:thelementofeachrowcomesfrommixingthecoloursinpositionsiandi+1ofthepreviousrow.Rinseandrepeatuntilonlythesingletonelementofthebottom row remains, returned as the 0inal answer. For example, starting from the 0irst row'rybyr'leadsto'brrb',whichleadsto'yry',whichleadsto'bb',whichleadsto'b'forthe0inalanswer,Regis.WhenthePythonvirtualmachinelaughinglygoes'brrrrr',thatwillleadto'yrrrr','brrr','yrr',and'br'forthe0inalanswer'y'for“Yes,please!”

(Today's0ive-dollarpowerwordtoastonishyourfriendsandcoworkersis"quasigroup".)

colours Expectedresult

'y' 'y'

'bb' 'b'

'rybyry' 'r'

'brybbr' 'r'

'rbyryrrbyrbb' 'y'

'yrbbbbryyrybb' 'b'

Count dominators

def count_dominators(items):

Weshallde0ineanelementofalistofitems tobeadominator ifeveryelementtoitsright(notjust theoneelement that is immediately to itsright) isstrictlysmaller thanthatelement.By thisde0inition, the last item of the list is automatically a dominator. This function should count howmanyelementsinitemsaredominators,andreturnthatcount.Forexample,thedominatorsofthelist[42, 7, 12, 9, 13, 5]wouldbeitselements42,13and5.Thelastelementofthelististriviallyadominator,regardlessofitsvalue,sincenothinggreaterfollowsit.

Before starting to write code for this function, you should consult the parable of "Shlemiel thepainter"andthinkhowthisseeminglysillytalefromasimplertimerelatestotoday'scomputationalproblemsperformedon lists, stringsandothersequences.Thisproblemwillbe the 0irstofmanythatyouwillencounterduringandafter thiscourse to illustrate the importantprincipleofusingonlyonelooptoachieveinatinyfractionoftimethesameendresultthatShlemielachieveswithtwonested loops.Yourworkload therefore increasesonly linearlywithrespect to thenumberofitems, whereas the total time of Shlemiel’s back-and-forth grows quadratically, that is, as afunctionofthesquareofthenumberofitems.

Trying tohide the inner loopofsomeShlemielalgorithminsidea functioncall (andthis includesPythonbuilt-inssuchasmaxandlistslicing)andpretendingthatthissomehowmakesthoseinnerloops take a constant time will only summon the Gods of Compubook Headings to return withtumulttoclaimtheirlion'sshareofexecutiontime.

items Expectedresult

[42, 7, 12, 9, 2, 5] 4

[] 0

[99] 1

[42, 42, 42, 42] 1

range(10**7) 1

range(10**7, 0, -1) 10000000

Beat the previous

def extract_increasing(digits):

Givenastringofdigitsguaranteed toonlycontainordinary integerdigitcharacters0 to9,createand return the list of increasing integers acquired fromreading thesedigits inorder from left toright.The0irstintegerintheresultlistismadeupfromthe0irstdigitofthestring.Afterthat,eachelement isan integerthatconsistsofasmanyfollowingconsecutivedigitsasareneededtomakethatintegerstrictlylargerthanthepreviousinteger.Theleftoverdigitsattheendofthedigitstringthatdonotformasuf0icientlylargeintegerareignored.

This problem can be solvedwith a single for-loop through thedigits that looks at each digitexactlyonce regardlessof thepositionof thatdigit in thebeginning, endormiddleof the string.Keep trackof thecurrent number (initially zero)and theprevious number tobeat (initiallyequaltominusone).Eachdigitd isthenprocessedbypinningitattheendofcurrent numberwiththeassignmentcurrent=10*current+int(d).

digits Expectedresult

'600005' [6]

'045349' [0, 4, 5, 34]

'77777777777777777777777' [7, 77, 777, 7777, 77777, 777777]

'122333444455555666666' [1, 2, 23, 33, 44, 445, 555, 566, 666]

'2718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260'

[2, 7, 18, 28, 182, 845, 904, 5235, 36028, 74713, 526624, 977572, 4709369, 9959574, 96696762, 772407663, 3535475945, 7138217852, 51664274274, 66391932003, 599218174135, 966290435729]

'1234' * 100 Alistwith38elements,thelastoneequalto341234123412341234123

'420' * 420 Alistwith56elements,thelastoneequalto420420420420420420420420420420420420420420

Subsequent words

def words_with_letters(words, letters):

Thisproblem is anexcuse to introduce somegeneraldiscretemath terminology thathelpsmakemanylaterproblemspeci0icationslessconvolutedandambiguous.Asubstringofastringconsistsofcharacterstakeninorder fromconsecutivepositions.Contrastthiswiththesimilarconceptofsubsequence of characters still taken in order, but not necessarily at consecutive positions. Forexample,eachof the 0ivestrings'','e','put','ompu' and'computer' isbothasubstringandsubsequenceofthestring'computer',whereas'cper' and'out' aresubsequences,butnotsubstrings.

Note how the empty string is always a substring of every possible string, including itself. Everystring is always itsownsubstring, althoughnot apropersubstring the samewayhowall othersubstringsareproper.Conceptsofsublistandsubsequencearede0inedfor lists inananalogousmanner.Sincesetshaveno internalorderontopof theelementmembership inthatset,setscanmeaningfullyhavebothproperandimpropersubsets,whereastheconceptof“subsetquence”mightmean a subset that would be a subsequence, were the members of that set were written outsequentiallyinsortedorder.

Now that you know all that, given a list ofwords sorted in alphabetical order, and a string ofrequiredletters,0indandreturnthelistofwordsthatcontainlettersasasubsequence.

letters Expectedresult(usingthewordlistwords_sorted.txt)

'klore' ['booklore', 'booklores', 'folklore', 'folklores', 'kaliborite', 'kenlore', 'kiloampere', 'kilocalorie', 'kilocurie', 'kilogramme', 'kilogrammetre', 'kilolitre', 'kilometrage', 'kilometre', 'kilooersted', 'kiloparsec', 'kilostere', 'kiloware']

'brohiic' ['bronchiectatic', 'bronchiogenic', 'bronchitic', 'ombrophilic', 'timbrophilic']

'azaz' ['azazel', 'azotetrazole', 'azoxazole', 'diazoaminobenzene', 'hazardize', 'razzmatazz']

Taxi ℤum ℤum

def taxi_zum_zum(moves):

AlonetaxicabcruisingthestreetgridoftheduskyManhattanthatweknowandlovefromclassichardboiled +ilmnoirworkssuchas“BlastofSilence”starts its journeyat theorigin(0,0) of thein0initetwo-dimensional integergrid,denotedbyℤ2.Fitting inthegauntandangularspiritof thetimethattoleratesfewdeviationsorgreyareas,thetaxicabisatalltimesheadedstraightinoneofthefourmainaxisdirections,initiallynorth.

This taxicab then executes the given sequence ofmoves, given as a string of characters'L' forturning90degreesleftwhilestandinginplace(justincasewearemakingaturnbackwards,incaseyouspottedsomegladragsorsomeout-of-townpalooka looking tobe taken foraride),'R' forturning90degrees right (ditto), and'F' formovingoneblock forward to currentheading.Thisfunction should return the 0inal position of the taxicab on this in0initely spanning Manhattan.(Before the reader objects to the idea ofManhattanization of everything, perhaps the rest of theworldlazilysimulatesthisin0initestreetgridwithmirrors?)

Asanaside,whydo theseproblemsalwaysseemto takeplace inManhattanandevokenostalgicvisualsofJackieMasonorthatWoodsyAllenfellowwiththegrumpyimmigrantcabbieandvariouscolourfulbystandercharacters,insteadofbeingsetin,say,themilehighcityofDenverwhosestreetgrid is rotated 45 degrees from themain compass axes to cleverly equalize the amount of dailysunlightonstreets inbothorientations?Thatought tomake foran interestingvariation tomanyproblems of this spirit. Unfortunately, diagonal moves always maintain the total parity of thecoordinates,whichmakesitimpossibletoreachanycoordinatesofoppositeparityinthismanner,asinthatoldjokewiththepunchline“Gee...Idon'tthinkthatyoucangettherefromhere.”

moves Expectedresult

'RFRL' (1, 0)

'LFFLF' (-2, -1)

'LLFLFLRLFR' (1, 0)

'FR' * 1729 (0, 1)

'FFLLLFRLFLRFRLRRL' (3, 2)

Exact change only

def give_change(amount, coins):

Given theamount ofmoney,expressedasan integeras the totalnumberofkopecksofPoldavia,Ruritania,MontenegroorsomeothersuchvaguelyEasternEuropean 0ictionalcountry thatTintinandsimilarheartyfellowswouldvisit,followedbythelistofavailabledenominationsofcoinsalsoexpressed as kopecks, this function should create and return a list of coins that add up to theamount using thegreedy approachwhere you use asmany of the highest denomination coinswhenpossiblebeforemovingontothenextlowerdenomination.Thelistofcoindenominationsisguaranteedtobegivenindescendingsortedorder,asshouldyourreturnedresultalsobe.

Thisproblem,alongwith its countlessvariations, is a computer scienceclassicwhenmodi0ied tominimizethetotalnumberofreturnedcoins.Theabovegreedyapproachthennolongerproducesthe optimal result for all possible coin denominations. For example, using simple coindenominationsof[50, 30, 1] and theamountofsixtykopecks tobeexchanged, thegreedysolution[50, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] endsupusingelevencoinsbyitsunfortunate0irstchoicethatpreventsitfromusinganyofthe30-kopeckcoinsthatwouldbehandyhere, seeing that the optimal solution[30, 30] needs only two such coins!Amore advancedrecursive algorithm examines both sides of the “take it or leave it” decision for each coin andchooses the choice that ultimately leads to a superior outcome. The intermediate results of thisrecursionshouldthenbememoizedtoavoidblowinguptherunningtimeexponentially.

amount coins Expectedresult

64 [50, 25, 10, 5, 1] [50, 10, 1, 1, 1, 1]

123 [100, 25, 10, 5, 1] [100, 10, 10, 1, 1, 1]

100 [42, 17, 11, 6, 1] [42, 42, 11, 1, 1, 1, 1, 1]

Rooks on a rampage

def safe_squares_rooks(n, rooks):

A generalized n-by-n chessboard has been invaded by a parliament of rooks, each rookrepresentedasatwo-tuple(row, column)oftherowandthecolumnofthesquarethattherookis in. Sincewe are again computer programmers instead of chess players and other healthy andnormalfolks,ourrowsandcolumnsarenumberedfrom0ton-1.Achessrookcoversallsquaresthatareinthesameroworinthesamecolumn.Giventheboardsizenandthelistofrooksonthatboard,countthenumberofemptysquaresthataresafe,thatis,arenotcoveredbyanyrook.

Toachievethis inreasonabletimeandmemory,youshouldcountseparatelyhowmanyrowsandcolumnsontheboardaresafefromanyrook.Becausepermutingtherowsandcolumnsdoesnotchangetheanswertothisquestion,youcanimagineallthesesaferowsandcolumnstohavebeenpermuted to form an empty rectangle at the top left corner of the board. The area of that saferectangleisthenobviouslytheproductofitsknownwidthandheight.

n rooks Expectedresult

10 [] 100

4 [(2, 3), (0, 1)] 4

8 [(1, 1), (3, 5), (7, 0), (7, 6)] 20

2 [(1, 1)] 1

6 [(r, r) for r in range(6)] 0

100 [(r, (r*(r-1))%100) for r in range(0, 100, 2)] 3900

10**6 [(r, r) for r in range(10**6)] 0

Try a spatula

def pancake_scramble(text):

Analogousto0lippingastackofpancakesbystickingaspatulainsidethestackand0lippingoverthestackofpancakesrestingontopofthatspatula,apancake<lipoforderkperformedforthetextstring reverses the pre0ix of 0irst k characters and keeps the rest of the string as it were. Forexample, thepancake0lipoforder2performedonthestring'ilkka' wouldproducethestring'likka'.Thepancake0lipoforder3performedonthesamestringwouldproduce'klika'.

Apancakescramble,asde0inedintheexcellentWolframChallengesprogrammingproblemssite,consistsofthesequenceofpancake0lipsoforder2,3,...,nperformedinthisexactsequenceforthegiven n-charactertext string. For example, the pancake scramble done to the string'ilkka'would step through the intermediate results'likka','kilka','klika' and'akilk'. Thisfunctionshouldcomputethepancakescrambleofitsparametertextstring.

Forthoseofyouwhoare interested inthissortofstuff, the follow-upquestion"Howmanytimesyouneedtopancakescramblethegivenstringtogetbacktheoriginalstring?"isalsoeducational,especiallyoncethestringsgetsolongthattheanswerneedstobecomputedanalytically(notethattheanswerdependsonlyonthelengthofthestringbutnotthecontent,aslongasallcharactersaredistinct) insteadof actuallyperforming these scramblesuntil theoriginal stringappears.Amorefamousproblemofpancakesortingasksfortheshortestseriesofpancake0lipstosortthegivenlist.

text Expectedresult

'hello world' 'drwolhel ol'

'ilkka' 'akilk'

'pancake' 'eanpack'

'abcdefghijklmnopqrstuvwxyz' 'zxvtrpnljhfdbacegikmoqsuwy'

'this is the best of the enterprising rear'

're nsrrteetf sbets ithsi h eto h nepiigra'

Words with given shape

def words_with_given_shape(words, shape):

The shapeof the givenwordof lengthn is a list ofn - 1 integers, each one either -1, 0 or +1 toindicatewhetherthenextletterfollowingtheletterinthatpositioncomeslater(+1),isthesame(0)orcomesearlier(-1)inthealphabeticalorderofEnglishletters.Forexample,theshapeoftheword'hello'is[-1, +1, 0, +1],whereastheshapeof'world'is[-1, +1, -1, -1].Findandreturnalistofallwordsthathavethatparticularshape,listedinalphabeticalorder.

Notethatyourfunction,sameasalltheotherfunctionsspeci0iedinthisdocumentthatoperateonlists of words, should not itself try to read the wordlist 0ile words_sorted.txt, even whenPythonmakesthispossiblewithjustacoupleoflinesofcode.Thetesterscriptalreadyreadsintheentirewordlistandbuilds the listofwords fromthere.Your functionshoulduse thisgiven listofwordswithoutevencaringwhichparticular0ileitcamefrom.

Motivated students can take on as a recreational challenge to 0ind the shape of lengthn - 1 thatmatchesthelargestnumberofwords,forthepossiblevaluesofnfrom3to20.Alternatively,trytocounthowmanypossibleshapesoflengthn-1donotmatchanywordsoflengthnatall.Whatistheshortestpossibleshapethatdoesnotmatchanywords?

shape Expectedresult(usingwordlistwords_sorted.txt)

[1, -1, -1, -1, 0, -1] ['congeed', 'nutseed', 'outfeed', 'strolld']

[1, -1, -1, 0, -1, 1] ['axseeds', 'brogger', 'cheddar', 'coiffes', 'crommel', 'djibbah', 'droller', 'fligger', 'frigger', 'frogger', 'griffes', 'grogger', 'grommet', 'prigger', 'proffer', 'progger', 'proller', 'quokkas', 'stiffen', 'stiffer', 'stollen', 'swigger', 'swollen', 'twiggen', 'twigger']

[0, 1, -1, 1] ['aargh', 'eeler', 'eemis', 'eeten', 'oopak', 'oozes', 'sstor']

[1, 1, 1, 1, 1, 1, 1] ['aegilops']

Chirality

def is_left_handed(pips):

Even though this has no effect on fairness, pips fromone to six are not painted ondice just anywhichway,butsothatpipsontheoppositefacesalwaysadduptoseven.(Thisconventionmakesiteasiertotellwhensomeonetriestousecrookeddicewithcertainundesirablepipvaluesreplacedwithmoreamenableones.)Ineachofthe23=8cornersofthecube,exactlyonevaluefromeachpairofforbiddenopposites1-6,2-5and3-4meetstwovalueschosenfromtheothertwopairsofforbiddenopposites.Youcantwistandturnanycornerofthedietofaceyou,andyettwooppositesidesnevercometogetherintosimultaneousview.

This discipline still allows for two distinct ways to paint the pips. If the numbers in the cornersharedbythefaces1,2,and3readoutclockwiseas1-2-3,thatdieisleft-handed,whereasiftheyreadoutas1-3-2,thatdieisright-handed.Analogoustoapairofshoesmadeseparatelyfortheleftandrightfoot, left-andright-handeddiceareinonesenseidentical,andyetagainnomatterhowyoutwistandturn,youcan'tseriouslyputeithershoeintheotherfootthantheoneitwasdesignedfor. (At least notwithout taking that three-dimensional pancake “Through the Looking-Glass” by0lippingitaroundinthefourthdimension!)

Thethreenumbersreadaroundanyothercornerstampthethreenumbersintheunseenoppositesides,andthereforedeterminethehandednessofthatentirediejustas0irmly.Giventhethree-tupleofpipsreadclockwisearoundacorner,determinewhetherthatdieisleft-handed.Thereareonly23*3! = 8*6 = 48possible pip combinations to test for, so feel free to exploit these four two-foldsymmetriestosimplifyyourcode.(Thisproblemwouldcertainlymakeforaninterestingexercisecodegolf,adisciplinethatweotherwisefrowninthiscourseasthefalsesteconomy.)

After solving that, imagine that our physical space had k dimensions, instead ofmerely just thefamiliar three.Howwoulddice evenbecast (inboth sensesof thisword) ink dimensions?Howwouldyougeneralizeyourfunctionto0indthechiralityofanarbitraryk-dimensionaldie?

pips Expectedresult

(1, 2, 3) True

(1, 3, 5) True

(5, 3, 1) False

(6, 3, 2) True

(6, 5, 4) False

The card that wins the trick

def winning_card(cards, trump=None):

Playing cards are again represented as tuples of (rank,suit) as in the cardproblems.pylectureexampleprogram. In trick taking games suchaswhist orbridge, fourplayerseachplayonecardfromtheirhandtothetrick,committingtotheirplayinclockwiseorderstartingfromtheplayerwhoplays0irstintothetrick.Thewinnerofthetrickisdeterminedbythefollowingrules:

1. Ifoneormorecardsofthetrumpsuithavebeenplayedtothetrick,thetrickiswonbythehighestrankingtrumpcard,regardlessoftheothercardsplayed.

2. Ifnotrumpcardshavebeenplayedtothetrick,thetrickiswonbythehighestcardofthesuitofthe0irstcardplayedtothetrick.Cardsofanyothersuits,regardlessoftheirrank,arepowerlesstowinthattrick.

3. Aceisthehighestcardineachsuit.

Note that theorder inwhich the cardsareplayed to the trickgreatlyaffects theoutcomeof thattrick, since the 0irstcardplayed in the trickdetermineswhichsuitshave thepotential towin thetrickinthe0irstplace.Returnthewinningcardforthelistofcardsplayedtothetrick.

cards trump Expectedresult

[('three', 'spades'), ('ace', 'diamonds'), ('jack', 'spades'), ('eight', 'spades')]

None ('jack', 'spades')

[('ace', 'diamonds'), ('ace', 'hearts'), ('ace', 'spades'), ('two', 'clubs')]

'clubs' ('two', 'clubs')

[('two', 'clubs'), ('ace', 'diamonds'), ('ace', 'hearts'), ('ace', 'spades')]

None ('two', 'clubs')

Do you reach many, do you reach one?

def knight_jump(knight, start, end):

Anordinarychessknightonatwo-dimensionalboardofsquarescanmakean“L-move”intouptoeightpossibleneighbours.However,ashassooftenbeendepictedinvariousworksofspaceopera,higher beings can generalize the chessboard to k dimensions from our puny two. A naturalgeneralizationof theknight'smovewhilemaintaining itsspirit is tode0ine thepossiblemovesassomek-tupleofstrictlydecreasingnonnegativeintegeroffsets.Eachoneofthesekoffsetsmustbeused forexactlyonedimensionofyourchoiceduring themove,eitherasapositiveoranegativeversion,todeterminethesquarewherethek-knightwillteleportastheunseenhandoftheplayermovesittherethroughthedimensionk+1.

Given thestart andend positions as k-tuples of integer coordinates, determine whether theknightcouldlegallymovefromstarttoendinasingleteleportingjump.

Aquickcombinatorialcalculationrevealsthatexactlyk!*2kpossibleneighboursarereachableinasinglemove,minus themoves that jump outside the board. In this notation, the ordinary chessknightisa(2,1)-knightthatreaches2!*22=8neighboursinonejump.A6-dimensionalknightcould reach awhopping 6! * 26 = 46080 different neighbours in one jump! Since the number ofmovesemanatingfromeachpositiontoitsneighboursgrowsexponentiallywithrespecttok,prettymucheverythingendsupbeingclosetoalmosteverythingelseinhigh-dimensionalspaces,givingpredatorstoomuchofanedgeoverthepreyforlifetoevolvethere.

knight start end Expectedresult

(2, 1) (12, 10) (11, 12) True

(7, 5, 1) (15, 11, 16) (8, 12, 11) True

(9, 7, 6, 5, 1) (19, 12, 14, 11, 20)

(24, 3, 20, 11, 13)

False

Sevens rule, zeros drool

def seven_zero(n):

SevenisconsideredaluckynumberinWesterncultures,whereaszeroiswhatnobodywantstobe.Letusbrie0lybringthesetwooppositestogetherwithoutlettingitbecomesomekindofemergencyby looking at positive integers that consist of some solid sequence of sevens, followed by some(possibly empty) solid sequence of zeros. Examples of integers of this form are 7, 7700, 77777,77777700, and 70000000000000. A surprising theorem proves that for any positive integer n,thereexist in0initelymany integersof such seven-zero form that aredivisiblebyn. This functionshould0indthesmallestsuchseven-zerointeger.

Even thoughdiscretemath andnumber theoryhelp, this exercise is not about comingupwith acleversymbolicformulaandtheproofofitscorrectness.Thisproblemisaboutiteratingthroughthenumbersofthisconstrainedformofsevensandzerosef0icientlyandcorrectlyinstrictlyascendingorder, so that the function can mechanistically 0ind the smallest working number of this formwithouthavinganyideaofwhythatnumberisthesmallestworking.(Orhavinganideaofanything,forthatmatter.Docomputersdreamofelectricsheep?)

Thislogicmightbebestwrittenasageneratortoyieldsuchnumbers.Thebodyofthisgeneratorconsistsoftwonestedloops.Theouterloopiteratesthroughthenumberofdigitsdinthecurrentnumber.Foreachd,theinnerloopiteratesthroughallpossiblekfromonetodtocreateanumberthatbeginswithablockofksevens,followedbyablockofd-kzeros.Mostofitsworkdoneinsidethathelpergenerator,theseven_zerofunctionitselfwillbeshortandsweet.

ThisproblemisadaptedfromtheexcellentMITOpenCoursewareonlinetextbook“MathematicsforComputerScience” (PDF link to the2018version foranybody interested) that, likesomanyothernon-constructivecombinatorialproofs,usesthepigeonholeprincipletoprovethatsomesolutionmustexistforanyintegern,butprovidesnoclueaboutwheretoactually0indthatsolution.Alsoasproveninthatsametextbook,whenevernisnotdivisiblebyeither2or5,thesmallestsuchnumberwillalwaysconsistofsomesolidsequenceofsevenswithnozerodigitsafterthem.Thiscanspeedupthesearchbyanorderofmagnitudeforsuchfriendlyvaluesofn.

n Expectedresult

17 7777777777777777

42 7770

103 7777777777777777777777777777777777

77700 77700

2**50 700000000000000000000000000000000000000000000000000

12345 (abehemoththatconsistsof822sevens,followedbyasinglezero)

Fulcrum

def can_balance(items):

Each element in items is a positive integer, in this problems semantically considered to be aphysicalweight, as opposed to, say, the current countof chickens.Your task is to 0ind a fulcrumpositioninthislistofweightssothatwhenbalancedonthatposition,thetotaltorqueoftheitemstotheleftofthatpositionequalsthetotaltorqueoftheitemstotherightofthatposition.Theitemonthefulcrumisassumedtobecenteredsymmetricallyonthefulcrum,anddoesnotparticipateinthetorquecalculation.

Inphysics,thetorqueofanitemwithrespecttothefulcrumequalsitsweighttimesdistancefromthe fulcrum. If a fulcrum position exists, return that position. Otherwise return -1 to arti0iciallyindicatethatthegivenitemscannotbebalanced,atleastwithoutrearrangingthem.

The problemof 0inding the fulcrumpositionwhen rearranging elements is allowedwould be aninteresting but a more advanced problem normally suitable for a third year computer sciencecourse.However,thisalgorithmcouldbebuiltinaneffective(althoughnotasef+icient)bruteforcefashionaroundthisfunctionbyusingthegeneratorpermutationsinthePythonstandardlibrarymoduleitertoolstotryoutallpossiblepermutationsinanouterloopuntiltheinnerloop0indsonepermutationthatbalances.(In fact,quitea fewproblemsof thisstylecanbesolvedwiththis“generateandtest”approachwithoutthebacktrackingalgorithmsfromthirdyearcourses.)

items Expectedresult

[6, 1, 10, 5, 4] 2

[10, 3, 3, 2, 1] 1

[7, 3, 4, 2, 9, 7, 4] -1

[42] 0

Fail while daring greatly

def josephus(n, k):

Theancientworldofswordsandsandals“🎶 whenmenweremadeof ironandtheirshipswere

madeofwood🎶 ”couldoccasionallyalsobeanentertaininglyviolentplace,atleastaccordingtopopular historical docudramas such as “300”, “Spartacus” and “Rome”. During one particularlymemorable incident, a group of zealots (yes, Lana, literally) found themselves surrounded byoverwhelmingRomanforces.Toavoidcaptureandarduousdeathbycruci0ixion,intheirrighteouszealthesemencommittedthemselvestomasssuicideinawaythatensuredeachman’sunwaveringcommitmenttothissharedfate.Theyarrangedthemselvesinacircle,andusedlotstochooseastepsizek.Thenrepeatedlycountkmenahead,killhimandremovehiscorpsefromthisgrimcircle.

Beingnormalpeopleinsteadofcomputerscientists,thisdeadlygameofeeny-meeny-miney-moeisone-based,andcontinuesuntilthelastmanstandingfallsonhisownswordtocompletethecircle.Josephuswouldverymuchprefertobethislastman,sincehehasotherideasofsurviving.Helphimsurvivewithafunctionthat,givennandk,returnsthelistoftheexecutionordersothatthesemenknowwhichplaces let thembe the survivorswhoget towalk away from this grim circle.A cutemathematical solution instantly determines the survivor for k = 2. Unfortunately k can getarbitrarilylarge,evenfarexceedingthecurrentnumberofmen…ifonlytobrie0lyexciteuscoldandtimidsouls,hollowmenwithoutchests,therictusofourblacklipsgapedingrimacethatsneersatthe strong men who once stumbled. (If only to lighten up this hammy lament, note the felinegeneralizationofthisproblemthatpracticallybegstobeturnedintoanadorableviralvideo.)

n k Expectedresult

4 1 [1, 2, 3, 4]

4 2 [2, 4, 3, 1]

10 3 [3, 6, 9, 2, 7, 1, 8, 5, 10, 4]

8 7 [7, 6, 8, 2, 5, 1, 3, 4]

30 4 [4, 8, 12, 16, 20, 24, 28, 2, 7, 13, 18, 23, 29, 5, 11, 19, 26, 3, 14, 22, 1, 15, 27, 10, 30, 21, 17, 25, 9, 6]

10 10**100 [10, 1, 9, 5, 2, 8, 7, 3, 6, 4]

All your fractions are belong to base

def group_and_skip(n, out, ins):

Apileofnidenticalcoinsliesonthetable.Eachmoveconsistsofthreestages.First,thecoinsintheremainingpilearearranged intogroupsofexactlyout coinspergroup,whereout isapositiveintegergreaterthanone.Second,then%out leftovercoinsthatdidnotmakeacompletegroupofout elementsaretakenasideandrecorded.Third, fromeachcompletegroupofout coinstakenout,exactlyinscoinsarecollectedtotogethercreatethenewsinglepile,therestofthecoinsagainputasideforgood.

Repeat this three-stagemoveuntil theentirepilebecomesempty,whichmusteventuallyhappenwheneverout>ins.Returnalistofhowmanycoinsweretakenasideineachmove.

Asyoucanseeinthe0irstthreerows,thismethodproducesthedigitsofthenonnegativeintegerninbaseoutinreverseorder.Sothisentiresetupturnedouttobeacleverlydisguisedalgorithmtoconstructtherepresentationofintegerninbaseout.However,animprovementoverthestandardbase conversion algorithm is that this version works not only for integer bases, but allows anyfraction out/ins that satis0ies out>ins and gcd(out,ins)==1 to be used as a base! Forexample,thefamousinteger42wouldbewrittenas323122inbase4/3.

Yes, fractional bases are an actual thing. Take a deep breath to think about the implications(hopefullysomethinghigherthanwinningabarbet),andthenimaginetryingtodorealworldbasicarithmetic in sucha system.That certainlywouldhavebeensome"NewMath" for the frustratedparentsintheswingingsixtiesforwhombalancingtheirchequebooksinthefamiliarbasetenwasalreadyanexasperatingordeal!

n out ins Expectedresult

123456789 10 1 [9, 8, 7, 6, 5, 4, 3, 2, 1]

987654321 1000 1 [321, 654, 987]

255 2 1 [1, 1, 1, 1, 1, 1, 1, 1]

81 5 3 [1, 3, 2, 0, 4, 3]

10**9 13 3 [12, 1, 2, 0, 7, 9, 8, 11, 6, 8, 10, 5, 8, 3]

Recamán's sequence

def recaman_item(n):

Compute and return then:th term of the Recaman's sequence. See the linked de0inition for thissequenceonWolframMathworld.

Note how the de0inition for the current element in this sequence depends on whether someparticularnumbercanbefoundinthepreviouslygeneratedpre0ixofthesequence.Toallowyourfunctiontoexecuteinasureandspeedyfashionevenformillionsofelements,youshoulduseasettokeeptrackofwhichelementsarealreadypartofthepre0ixofthesequencegeneratedsofar.Thiswayyoucangenerateeachelementinconstanttime,insteadofhavingtoiteratethroughtheentirepreviouslygeneratedlistthewaysome"Shlemiel"mightapproachthisproblem.

The previous version of this problem, simply called recaman in the very 0irst versions of thisproblemcollection,expectedthisfunctiontoreturntheentiresequenceuptothen:thterm.Thisdatesallthewaybacktotheoriginalautomatedtesterscriptthatcomputedonlythechecksumofexpected answers, but did not record or reveal the expected answers to aid students in theirdebuggingtasks.Sincetheexpected_answers0iledidnotevenexistatthetime,havingtostorehundredsofthousandsofintegersinsidethat0ilewasnotrelevant.

n Expectedresult

1 1

8 12

13 23

57 87

395743 258330

Count the balls off the brass monkey

def pyramid_blocks(n, m, h):

Mysteries of the pyramids have fascinated humanity through the ages. Instead of packing yourmachete andpith helmet to trek throughdeserts and jungles to raid thehidden treasures of theancients like some Indiana Croft, or by gaining visions of enlightenment by intenselymeditatingundertheapexsetoverasquarebaselikesomeDeepakVeidt,thisproblemdealswithsomethingabitmoremundane;truncatedbrassmonkeysoflayersofdiscreteuniformspheres,inspiritofthatsphericalcowrunninginavacuum.

Giventhatthetoplayerofthetruncatedbrassmonkeyconsistsofnrowsandmcolumnsofspheres,andeach solid layer immediatelybelow theoneabove it always containsonemore rowandonemorecolumn,howmanyspheresintotalmakeupthistruncatedbrassmonkeythathashlayers?

Thisproblemcouldbesolvedinastraightforwardbruteforce fashionbymechanisticallytallyingupthespheres iteratedthroughthese layers.However, the justrewardfornaughtyboysandgirlswhotakesuchabluntapproach is toget towatch theautomated tester takeroughlyaminute toterminate!Somecreativeuseofdiscretemathandsummationformulasgivesananalyticalclosedformformula thatmakes theanswerscomeout faster thanyoucansnapyour 0ingerssimplybypluggingthevaluesofn,mandhintothisformula.

Asanunrelatednote,asniceasPythoncanbeforcasualcodingbyliberatingusfromallthatlowlevelnittygritty,Wolframisanothergreatlanguagewithgreatonlinedocumentation.YoucanplayaroundwiththislanguageforfreeonWolframCloudtotryoutnotjustallthecoolone-linersfromthe tutorials and documentation pages, but evaluate arbitrarymathematical expressions of yourown,forexampleSum[(n+i)(m+i), {i, 0, h-1}],inafullysymbolicfashion.

n m h Expectedresult

2 3 1 6

2 3 10 570

10 11 12 3212

100 100 100 2318350

10**6 10**6 10**6 2333331833333500000

Count growlers

def count_growlers(animals):

Let thestrings'cat' and'dog' denote thatkindofanimal facing left,and'tac' and'god'denotethatsamekindofanimalfacingright.Sinceinthisdayandagethiswholesetupsoundslikesomekindofamemeanyway,letussomewhatunrealisticallyassumethateachindividualanimal,regardlessofitsownspecies,growlsifitseesstrictlymoredogsthancatstothedirectionthattheanimalisfacing.Givenalistofsuchanimals,returnthecountofhowmanyoftheseanimalsaregrowling.Intheexampleslistedbelow,thegrowlinganimalshavebeenhighlightedingreen.

(Iwillbe the 0irst toadmit that Iwashighasakitewhen I thoughtup thisproblem.Sometimesproblemsandtheirsolutionscanbehardtotellapart,asthatdistinctiondependsontheanglefromwhichyouviewthewholemessfrom.)

animals Expectedresult

['cat', 'dog'] 0

['god', 'cat', 'cat', 'tac', 'tac', 'dog', 'cat', 'god']

2

['dog', 'cat', 'dog', 'god', 'dog', 'god', 'dog', 'god', 'dog', 'dog', 'god', 'god', 'cat', 'dog', 'god', 'cat', 'tac']

11

['god', 'tac', 'tac', 'tac', 'tac', 'dog', 'dog', 'tac', 'cat', 'dog', 'god', 'cat', 'dog', 'cat', 'cat', 'tac']

0

Bulgarian solitaire

def bulgarian_solitaire(piles, k):

Infrontofyouarek*(k+1)//2 identicalpebbles,givenaspiles. (Thesepebblestotalthek:thtriangularnumberthatisequaltothesumofthepositiveintegersfrom1tok,foreverybuddinglittleGaussouttheretospeeduptheircomputations.)Boredoutofyourmind,youlazilyarrangethese pebbles around. Eventually you make a game out of it; seeing how many times you canarrangethesepebblesintoneatrowsinaday,thentryingtobreakthatrecord.

Anaptmetaphorforthebleakdaily lifebehindtheIronCurtain, inthissolitairegameallpebblesareidenticalandyoudon'thaveanychoiceinyourmoves.Eachmovepicksupexactlyonepebblefrom every pile (making piles with only one pebble vanish), and creates a new pile from thishandful.Forexample,the0irstmovefrom[7, 4, 2, 1, 1]turnsinto[6, 3, 1, 5].Thenextmoveturnsinto[5, 2, 4, 4],whichthenturnsinto[4, 1, 3, 3, 4],andsoon.

Thisfunctionshouldcounthowmanymovesleadfromtheinitialpilestothesteadystatewhereeach number from1 tok appears as the size ofexactly onepile, and return that count. Thesenumbersfrom1 tok mayappearinanyorder,notnecessarilysorted.(Applyingthemovetothissteadystatesimplyleadsrightbacktothatsamesteadystate,hencethename.)

This problem comes from the Martin Gardner column “Bulgarian Solitaire and Other SeeminglyEndlessTasks”.Itwasusedthereasanexampleofawhile-loopwhereitisnotimmediatelyobviousthat this loopwill alwayseventually reach itsgoaland terminate, analogous to theunpredictablebehaviouroftheCollatz3x+1problemseeninmathproblems.py.However,unlikeinthatstillannoyinglyopenproblem,Bulgariansolitairecanbeproventonevergetstuck,butreachthesteadystatefromanystartingcon0igurationoftriangularnumbersafteratmostk(k-1)/2steps.

piles k Expectedresult

[1, 4, 3, 2] 4 0

[8, 3, 3, 1] 5 9

[10, 10, 10, 10, 10, 5] 10 74

[3000, 2050] 100 7325

[2*i-1 for i in range(171, 0, -2)] 171 28418

Scylla or Charybdis?

def scylla_or_charybdis(moves, n):

Thisproblemwas inspiredby thearticle "AMagicalAnswer to the80-Year-OldPuzzle" inQuantaMagazine.Thankstoyourrecentcunningstunts,yournemesisinlife0indsherselftrappedinsideadeviousgamewhere,forarefreshingchangefromtheusualwayofthings,youplaytheFinalBoss.(Everyone is thehero in theirownstoryuntil theybecomeavillain in someoneelse's.)Her 0inalshowdown resembles an 8-bit video game one-dimensional platform that reaches n-1 discretestepsfromitscentertobothdirections,withbeepboopsoundeffectstocompletethemoodofthatera. At each end of this platform, exactly n steps from the center, your henchmen Scylla andCharybdisarealreadylickingtheirlipsinanticipationofatastymorseltofallinovertheedge.

Yournemesisstartsatthecenterofthisplatform,andmustbegintoimmediatelycommittingtoherentire sequenceof futuremoves as a stringof'+' (“🎶 just a step to the ri-i-i-i-ight🎶 ”) and'-'(moveonesteptotheleft).Yourtaskisto0indandreturnapositiveintegerksothatexecutingeveryk:th stepofmoves (so this subsequencestarts frompositionk-1 and includeseveryk:thelementfromthenon)makesyournemesisfallintoeitheroneofthetwopossibledoomsn stepsawayfromherstartingpointatthecenter.

If several values ofk do the job, return the smallest value ofk among those thatminimize thenumberof steps to thedownfall.Otherwise, those freakingTolkien eagleswill once again swoopdownandliftyournemesistosafety.Sheisthennearlyguaranteedtoreturninathirdyearcourseonanalysisofalgorithmsasanadversary toputyour functionsthroughawringerofwitswhereshegetstowieldthesamesecond-moveradvantagethatyougottoenjoythistime.

moves n Expectedresult

'-++--++-++++' 2 3

'--++++---+-++-+++++++++++' 5 5

'+-++---+-+-++-+++----+++-++-+---+--++++++++++' 5 7

'+--++---+-++-+++------+++++---++-+--+++-+--++-++-++-+-++++++++++++++++++'

9 1

Longest arithmetic progression

def arithmetic_progression(items):

Anarithmeticprogressionisanumericalsequenceinwhichthestridebetweentwoconsecutiveelementsstaysconstantthroughoutthesequence.Forexample,[4, 7, 10, 13, 16] isanarithmeticprogressionoflength5,startingfromvalue4withthestrideofthree.

Givenanon-empty listitems ofpositive integers instrictlyascendingorder, 0indandreturnthelongest arithmetic progressionwhose values exist inside that sequence. Return the answer as atuple(start, stride, n)forthethreecomponentsthatde0ineanarithmeticprogression.Toensureuniqueresultstofacilitateautomatedtesting,wheneverthereexistseveralprogressionsofthesamelength,thisfunctionshouldreturntheonewiththeloweststart.Ifseveralprogressionsofequallengthemanatefromtheloweststart,returntheprogressionwiththesmalleststride.

Bridgeplayers like todistinguishbetween “best resultpossible”and “bestpossible result”,whicharenotatallthesamething!Inthesamespirit,doyouseethedifferencebetweentwodeceptivelysimilarconceptsof“leftmostoflongest”and“longestofleftmost”?

items Expectedresult

[42] (42, 0, 1)

[2, 4, 6, 7, 8, 12, 17] (2, 2, 4)

[1, 2, 36, 49, 50, 70, 75, 98, 104, 138, 146, 148, 172, 206, 221, 240, 274, 294, 367, 440]

(2, 34, 9)

[2, 3, 7, 20, 25, 26, 28, 30, 32, 34, 36, 41, 53, 57, 73, 89, 94, 103, 105, 121, 137, 181, 186, 268, 278, 355, 370, 442, 462, 529, 554, 616, 646, 703]

(7, 87, 9)

range(1000000) (0, 1, 1000000)

Best one out of three

def tukeys_ninthers(items):

BackinthedaywhencomputerswerefarslowerandhadalotlessRAMfortheprogramstoburrowinto,specialtechniqueswerenecessarytoachievemanythingsthataretrivialtodaywithacoupleof lines of code. In this spirit, "Tukey's ninther" is an eponymous approximation algorithm toquickly 0indsomevalue“reasonablyclose” to themedianelementof thegivenunsorted list.Forthepurposesofthisproblem,themedianelementofthelistisde0inedtobetheelementthatwouldend up in themiddle position if that listwere actually sorted. This de0initionmakes themedianunambiguous regardless of the elements and their multiplicities. Note that this function is nottaskedto0indthetruemedian,whichwouldbeatrivialone-lineraftersortingtheitems,but0indandreturntheveryelementthatTukey'snintheralgorithmwouldreturnforthoseitems.

Tukey'salgorithmsplitsthelistintotripletsofthreeelements,and0indsthemedianofeachtriplet.Thesemedians-of-threearecollectedintoanewlistandthissameoperationisrepeateduntilonlyoneelementremains.Forsimplicity,yourfunctionmayassumethatthelengthofitemsisalwayssomepowerof three. In the following table,eachrowcontains theresultproducedbyapplyingasingleroundofTukey'salgorithmtothelistimmediatelybelowit.

Tukey's algorithm is extremelyrobust.This canbeappreciatedbygiving it abunchof randomlyshuf0led lists of distinct numbers to operate on, and admiring how heavily centered around theactualmedianthehistogramofresultsendsupbeing.Forexample,themedianofthelastexamplelist in theabove table is really15,pinkyswear forgrownuprealsies.Thesedistinctnumberscaneven come from distributions over arbitrarily wide scales, since thispurely comparison-basedalgorithmneverperformsanyarithmeticbetweenelements.Evenbetter, ifallitems aredistinctandthelengthofthelistissomepowerofthree,thereturnedresultcanneverbefromthetruetoporbottomthirdofthesortedelements(discretemathexercise:provethis),thuseliminatingallriskofusingsomefunkyoutlierastheapproximatemedian.

items Expectedresult

[15] 15

[42, 7, 15] 15

[99, 42, 17, 7, 1, 9, 12, 77, 15] 15

[55, 99, 131, 42, 88, 11, 17, 16, 104, 2, 8, 7, 0, 1, 69, 8, 93, 9, 12, 11, 16, 1, 77, 90, 15, 4, 123]

15

Collecting numbers

def collect_numbers(perm):

This problem is adapted from the problem "Collecting Numbers" in the CSES Problem Set. Youradversary has shrunk you to a microscopic scale and trapped you inside the computer. You arecurrentlystandingatthe0irstelementofperm,somepermutationofintegersfrom0ton-1,eachsuchnumber appearing in this list exactly once. The rules of this gamedictate that you are onlyallowedtomoverightandadvanceonlyoneelementatthetime,butneversteptotheleftorjumpover any elements. This list is treated as cyclic so that whenever you would step past the lastelement,youarrivebackatthebeginning,havinggoneonemoreroundaroundthelist.

Togetout,youmusttellyouradversaryassoonaspossiblehowmanyroundsitwouldtakeyoutocompletethetaskofcollectingtheelementsfrom0ton-1intheexactascendingorder.Followingthemovementrules,youwouldkeepgoingrightuntilyou0indtheelement0.Afterthat,youwouldkeepgoingrightuntilyou0indthenextelement1.Wheneveryoucometotheend,youstartanewroundfromthebeginning.Eventually,youwillhavecollectedallthenumbersthiswayinorderandbedone.Forexample,giventhepermutation[2, 0, 4, 3, 1],youcollect0and1duringthe0irst round. In the second round, you collect both 2 and 3. In the third round, you 0inally get tocollecttheremaining4andcallitaday,forthe0inalanswerofthreerounds.

Theimportantlessonofthisproblemisthatafunctionthatsimulatessomeothersystemasablackbox does not literally have to follow the rules of that system, but may use any computationalshortcutwhatsoeveraslongasthe0inalansweriscorrect!Therefore,beatyouradversarywith0lairby0irstconstructingtheinversepermutationofperm.This inversepermutationinv isanotherpermutation of integers from 0 to n-1 that satis0ies inv[i]==j whenever perm[j]==i. Forexample,theinverseofthepreviouspermutationis[1, 4, 0, 3, 2].Theinvlistallowsyoutoquickly lookupthe locationthatanyparticularelement isstoredat intheoriginalperm.Onceyourfunctionhas0irstconstructedinv,youwillbeabletocomputetherequirednumberofroundswithasinglefor-loopoverrange(0,n)thatdoesnotevenglanceattheoriginalpermduringitsexecution,sincethisloopgetsalltheinformationthatitneedsfromtheinvlistalone.

perm Expectedresult

[0, 1, 2, 3, 4, 5] 1

[2, 0, 1] 2

[0, 4, 3, 5, 2, 1] 4

[8, 6, 9, 5, 4, 11, 2, 0, 3, 10, 12, 1, 7] 7

list(range(10**6, -1, -1)) 1000001

Count Troikanoff, I presume

def count_troikas(items):

De0inethreepositions i< j<koftheitems listtoconstituteatroika iftheelementsinallthreepositionsareequal,andthepositionsthemselvesarespacedapartinanarithmeticprogression.More succinctly, these positions satisfy items[i]==items[j]==items[k] and j-i==k-j.Thisfunctionshouldcounthowmanytroikasexistinthegivenlistofitems.Forexample,thelist[42, 17, 42, 42, 42, 99, 42]containsfourtroikas,eachusingthevalue42.

This problem could be solved by inef0icient juggernauting through all equally spaced positiontriples(i,j,k).(Youonlyneedtoloopthroughiandj,sincethosenaildownk.)However,youcandobetterbybuildingadict-ionarywhosekeysaretheelementsthatappearsomewhereinitems.Eachvalueisasortedlistofpositionswherethatparticularkeyappearsinitems.Forthepreviousexamplelist,thisdictionarywouldbe{42: [0, 2, 3, 4, 6], 17: [1], 99: [5]}.

Then, loopthroughthekeysofthisdictionary.Foreachkey, loopthrougheverypositionpair i< jinto its value list (the decorator itertools.combinations again goes brrrrr, ha ha), andcompute the assumed third positionwith the formula k = j + (j - i). Ifitems[k]==items[i],incrementyourtroikacounter.Searchingfortroikasinthismannerwilltypicallyspendanorderofmagnitudelesstimechurningouttheanswerthanthe"Shlemiel"methodofbruteforce.Themoredistinctvaluestheseitemscover,thesharpertheedgeofthismoresophisticatedmethod.

items Expectedresult

[5, 8, 5, 5] 0

[-8, -8, -8, -18, -8, 13, -8] 3

[3, 6, 3, 6, 3, 6, 6, 6, 3] 5

[23, 23, 23, 23, 23, 23, 16, 23] 8

[21, 21, 21, 21, 21, 21, 21, -41, 21, 76, 21, -71, 47]

15

[42 for _ in range(100)] 2450

Crack the crag

def crag_score(dice):

CragisanolddicegamesimilartothemorepopulargamesofYahtzeeandPokerdiceinstyleandspirit, butwithmuch simpler combinatoricsof roll value calculationdue to this gameusingonlythreedice.Playersrepeatedlyrollthreediceandassigntheresultingpatternstoscoringcategoriesso that once some roll hasbeenassigned to a category, that category is considered tohavebeenspentandcannotbeusedagainforanyfutureroll.Thesetacticalchoicesbetweensafetyandrisk-takinggivethisgameamoretactical0lairontopofmerelyrelyingonthefavoursofLadyLuckforrollingthebones.SeetheWikipediapageforthescoringtableusedinthisproblem.

Given the list of pips of the three dice of the 0irst roll, this function should return the highestpossible score availablewhenall categoriesof the scoring tableare still available foryou tochoose from, so that all thatmatters ismaximizing this 0irst roll.Note that theexampleson theWikipediapageshowthescorethatsomedicewouldscoreinthatparticularcategory,whichisnotnecessarilyevenclosetothemaximumscoreinprincipleattainablewiththatroll.Forexample,theroll[1, 1, 1]usedinef0icientlyinthecategory“Ones”wouldindeedscoreonlythreepoints,whereasthesamerollscoresawhopping25pointsinthehardercategory“Threeofakind”.(Theproblem“Optimalcragscore”neartheendofthiscollectionhasyoudistributeaslewoftheserollsintodistinctcategoriestomaximizethetotalscore.)

This problem ought to be a straightforward exercise on if-else ladders combined with simplesequencemanagement. Your function should be swift and sure to return the correct answer forevery one of the 63 = 216 possible pip combinations. However, you will surely design yourconditionalstatementstohandleentireequivalenceclassesofpipcombinationsinasinglestep,sothatyourentireladderconsistsoffarfewerthan216separatesteps.

dice Expectedresult

[1, 2, 3] 20

[4, 5, 1] 5

[3, 3, 3] 25

[4, 5, 4] 50

[1, 1, 1] 25

[1, 1, 2] 2

Three summers ago

def three_summers(items, goal):

Given a sorted list of positive integer items, determine whether there exist precisely threeseparateitemsthattogetherexactlyadduptothegivenpositiveintegergoal.

Sure,youcouldsolvethisproblemwiththreenestedloopstogothroughallpossiblewaystochoosethree elements fromitems, checking for each triplewhether it adds up to thegoal. However,iterating through all triples of elementswould get pretty slowas the lengthof the list increases,seeing that the number of such triples to pick through grows proportionally to the cube of thelengthofthe list!Ofcoursetheautomatedtesterwillmakethoselists largeenoughtomakesuchsolutionsrevealthemselvesbytheirglacialrunningtime.

Sinceitemsareknowntobesorted,abettertechniquewill0indtheanswersigni0icantlyfaster.Seethe function two_summers in the example program listproblems.py to quickly 0ind twoelementsinthegivensortedlistthattogetheradduptothegivengoal.Youcanusethisfunctionasa subroutine to speedup your search for three summing elements, once you realize that the listcontainsthreeelementsthatadduptogoal ifandonlyifitcontainssomeelementx sothattheremaininglistcontainssometwoelementsthatadduptogoal-x.

For the general subset sum problem that was used as an example of inherently exponentialbranchingrecursioninthatlecture,thequestionofwhetherthegivenlistofintegerscontainssomesubsetofkelementsthattogetheradduptogivengoalcanbedeterminedbytryingeachelementx in turn as the 0irst element of this subset, and then recursively determining whether theremainingelementsafterxcontainsomesubsetofk-1elementsthataddsuptogoal-x.

items goal Expectedresult

[10, 11, 16, 18, 19] 40 True

[10, 11, 16, 18, 19] 41 False

[1, 2, 3] 6 True

Sum of two squares

def sum_of_two_squares(n):

Manypositiveintegerscanbeexpressedasasumofexactlytwosquaresofpositiveintegers,bothpossiblyequal.Forexample,74=49+25=72+52.Thisfunctionshould0indandreturnatupleoftwo positive integerswhose squares add up ton, or returnNone if the integern cannot be soexpressedasasumoftwosquares.

Thereturnedtuplemustpresentthelargerof itstwonumbers0irst.Furthermore, ifsomeintegercanbeexpressedasasumoftwosquaresinseveralways,returnthebreakdownthatmaximizesthelargernumber.Forexample,theinteger85allowstwosuchrepresentations72+62and92+22,ofwhichthisfunctionmustthereforereturn(9, 2).

The technique of two pointers, as previously seen in the function two_summers in thelistproblems.py example program, directly works also on this problem! The two positionsstart frombothendsof thesequence, respectively, fromwhere they inch towardseachother inawaythatguaranteesthatneithercaneverskipoverasolution.Thisprocessmusteventuallycometoade0initeoutcome,sinceoneofthetwothingsmusteventuallyhappen:eitheraworkingsolutionisfound,orthepositionsmeetsomewherebeforeever0indingasolution.

(Inbinary search, one of these indices would jump halfway towards the other in every round,causingtheexecutiontimetobelogarithmicwithrespectton.However,wearenotinsuchaluckysituationwiththissetup.)

n Expectedresult

1 None

2 (1, 1)

50 (7, 1)

8 (2, 2)

11 None

123**2 + 456**2 (456, 123)

55555**2 + 66666**2 (77235, 39566)

Carry on Pythonista

def count_carries(a, b):

Twopositiveintegersaandbcanbeaddedwiththeusualintegercolumn-wiseadditionalgorithmthat we all learned as wee little children so early that most people don't even think of thatmechanistic operation as an algorithm! Insteadof the suma+b that the languagewould alreadycomputeforyouanyway,thisproblemasksyoutocounthowmanytimestherewillbeacarryofoneintothenextcolumnduringthismechanisticaddition.Yourfunctionshouldbeef0icientevenforbehemothsthatconsistofthousandsofdigits.

Toextractthelowestdigitofapositiveintegern,usetheexpressionn%10.Toextractallotherdigitsexcept the lowest one, use the expression n//10. You can use these simple integer arithmeticoperationstotraipsethroughthestepsofthecolumn-wiseintegeradditionwhereyoudon'tcareabout the actual result of the addition, but only tally up the carries produced in each column asproofofworkofyouactuallylabouringthroughthestepsofthecolumn-wiseaddition.

a b Expectedresult

0 0 0

99999 1 5

11111111111 2222222222 0

123456789 987654321 9

2**100 2**100 - 1 13

10**1000 - 123**456 123**456 1000

As below, so above

def leibniz(heads, positions):

Regardless of your stance on the Pascal’s wager, betting that some rows of the famous Pascal’strianglewillbegeneratedduringyearoneortwoofyourcomputerscienceundergraduateprogramissafeashouses.Evenwithoutconsiderationtotheinterestingcombinatorialsequencesinsidethisin0initetable,merelytabulatingitsentriesisagoodlittleexerciseofusingnestedloops.

ThisproblemlooksatLeibniztriangles,acurious“upside-down”variationofthePascal’strianglewhereeachentryequalsthesumofthetwoentriesimmediatelybelow it, insteadofabove itthewaytheydidinPascal'striangle.Theimmediateproblemin0lippingthedirectionofthisrecursionisthatthisupside-downrecursionhasnobasecasesthatwouldeverallowittoterminate!InsteadofPascal'sbasecaseoftheunitybitatthetopwhoseunionwiththezerobitofthenonexistentvoidoutsidethen0illsintherestofthetriangle,theLeibniztrianglebranchesoutintoancacophonouspyramid of turtles all the way down to Dante's ten circles, whence the Adversary can 0ill it inuncountable(yes,Lana,literally)ways,eachmorediabolicalthanthenext.

Fortunatelyforuscloudsofdustdancinginthegreatwindthatcarriesusall,merelyde0iningtheheads,theleadingelementsofeveryrow,suf0icientlyconstrainsthisrecursiontoreinintherestofthetriangle.Shouldadisputeaboutsomevalueemerge,verywellthen,letussimplytakeoutourmechanistic step reckoners and calculate! One possible solution to this recursion is the originalLeibnizharmonictrianglethatcomesfromusingconsecutiveunitfractionsasheads.

ThisfunctionshouldimmanentizeasmanyrowsoftheLeibniztriangleasthereareheads given,using twonested loops tocompute theseentries.However, this functionneeds toreturnonly theentriesingivenpositionsofthe0inalgeneratedrow.Havingveri0iedthosetobecorrect,wecansafely assume your intermediate rows to also have been correct,without actually forcing you to“showyourwork”. (Eventhoughyoudohaveto loopthroughtherowsstarting fromthetop,youdon’tactuallyneedtoexplicitlystoreallofthem,butonlythecurrentrowanditspreviousrow.)

(ExtragoldstarsareawardedforstudentswhosecodeOl'Leibyhimselfwouldhavegrokked.)

heads positions Expectedresult

[3, 2] range(2) [2, 1]

[1, -1, 1, -1] range(4) [-1, 2, -4, 8]

range(6) range(6) [5, -1, 0, 0, 0, 0]

[Fraction(1, n) for n in range(1, 6)]

[4, 2] [Fraction(1, 5), Fraction(1, 30)]

Expand positive integer intervals

def expand_intervals(intervals):

Anintervalofconsecutivepositiveintegerscanbesuccinctlydescribedasastringthatcontainsits0irstandlastvalue,inclusive,separatedbyaminussign.(Thisproblemisintentionallyrestrictedtopositive integers so that therewill be no ambiguity between theminus sign character used as aseparator and an actual unaryminus sign tacked in front of a digit sequence.) For example, theintervalthatcontainstheintegers5,6,7,8,9canbemoreconciselydescribedas'5-9'.Multipleintervals can be described together by separating their descriptions with commas. A singletonintervalwithonlyonevalueisgivenasthatvalue.

Givenastringofsuchcomma-separatedintervals,guaranteedtobe insortedascendingorderandneveroverlaporbecontiguouswitheachother,thisfunctionshouldcreateandreturnthelistthatcontainsalltheintegerscontainedinsidetheseintervals.Insolvingthisproblem,thesameasanyotherproblems,itisalwaysbettertonothavetoreinventthewheel,but0irstcheckoutwhetherthestringobjectsofferanyusefulmethodsthatmakeyourjobeasier.

For purely aesthetic reasons, the problem is restricted to positive numbers. The above notationwould still be unambiguous even if the very sameminus sign character served twomasters byacting as both the element separator and the unaryminus sign. The internal state of the parseralwaysdecideswhateachcharacter,like,0inger-quotes"means"inthecurrentposition.

We also note how the different lengths of dashes and quotation marks pointing in differentdirectionstendnotbeusedincomputertext,despitethefactthattheyareUnicodesymbolsjustthesameasanyoldtimeyASCIIsymbol.(PerhapsASCIIstandsfor"ass-kiss"here.Go0igure.)

intervals Expectedresult

'' []

'42' [42]

'4-5' [4, 5]

'4-6,10-12,16' [4, 5, 6, 10, 11, 12, 16]

'1,3-9,12-14,9999' [1, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 9999]

Collapse positive integer intervals

def collapse_intervals(items):

Thisfunctionistheinverseofthepreviousproblemofexpandingpositiveintegerintervals.Givenanonempty list of positive integeritems guaranteed to be in sorted ascending order, create andreturntheuniquedescriptionstringwhereeverymaximalsublistofconsecutiveintegershasbeencondensedtothenotationfirst-last.Suchencodingdoesn’tactuallysaveanycharacterswhenfirst andlast differbyonlyone.However,itisusuallymoreimportantfortheencodingtobeuniformthantobepretty.Asageneralprinciple,uniformandconsistentencodingofdataallowstheprocessingofthatdatatoalsobeuniforminthetoolsdowntheline.

If somemaximalsublistconsistsofasingle integer, itmustbe included in theresult stringallbyitselfwithouttheminussignseparatingitfromthenowredundantlast number.Makesurethatthestringreturnedbyyourfunctiondoesnotcontainanywhitespacecharacters,andthat itdoesnothaveasillyredundantcommahangingattheend.

items Expectedresult

[1, 2, 4, 6, 7, 8, 9, 10, 12, 13] '1-2,4,6-10,12-13'

[42] '42'

[3, 5, 6, 7, 9, 11, 12, 13] '3,5-7,9,11-13'

[] ''

range(1, 1000001) '1-1000000'

Prominently featured

def prominences(height):

Theone-dimensional silhouetteofan island isgivenasaheight listof rawelevation valuesateach position, measured from the baseline at the sea level. To simplify things, this rocky andvolcanicislandisguaranteedtonotcontainanyplateaus,consecutivepositionsofequalelevation.Positionsoutsidetheheightlistareassumedtolieatsealevel.

Thisfunctionshouldreturnthelistofpeaksofthisisland,thatis,localpositionswhoseimmediateleftandrightneighbourslieatalowerelevation.Eachpeakisrepresentedasatuple(position, elevation, prominence).Theposition andelevation ofeachpeakare takendirectlyfrom the height list. As explained on the Wikipedia page “Topographical prominence”, theprominence of apeak is theminimumvertical descentnecessary to get to anystrictlyhigherpeak,whenyouget to choose thishigherpeakand the route freely tominimize thisdescent. (Intechnical terms,youmustdomaximinoptimization in choosing thebest route tomaximize theheightofitsminimumpoint.)Thelowestvalleyalongthisbestrouteisthekeycoloftheoriginalpeak,andthestrictlyhigherpeakreachedthroughthekeycolisitsparentpeak.Sincethehighestpeakoftheislandhasnokeycol,itsprominencesimplyequalsitsrawelevation.

Thisproblemwillsoongettrickyfortwo-dimensionalheight0ieldswithalltheensuingfreedomtogoaroundthings.Fortunately, in this farsimplerone-dimensionalversion,youcan 0irstconstructthe list of all the peaks and valleyswith one linear pass throughheight, as these are the onlyentriesthatarerelevantforthecalculationofprominences.Foreachpeak,proceedtotheleftuntilyou reach somehigherpeak,keeping track the lowestelevation seenalong theway.Thendo thesamethingagain,but this timegoingright fromthatsamestartingpeak.Thehigherof thesetwolowestvalleysisthekeycolthatletsyoucomputetheprominenceofthepeak.

height Expectedresult

[42] [(0, 42, 42)]

[1, 3] [(1, 3, 3]

[1, 3, 2, 5, 1] [(1, 3, 1), (3, 5, 5)]

[4, 2, 100, 99, 101, 2] [(0, 4, 2), (2, 100, 1), (4, 101, 101)]

[1, 10, 8, 10, 5, 11] [(1, 10, 5), (3, 10, 5), (5, 11, 11)]

[3, 5, 9, 12, 4, 3, 6, 11, 2] [(3, 12, 12), (7, 11, 8)]

Like a kid in a candy store, except without money

def candy_share(candies):

Agroupofchildrensitaroundinacirclesothateachchildhassomenumberofidenticalcandiesin front of them. To synchronize these children to move as a group in a logically simultaneousfashion,theteacherringsabelltomarkeachround.Ateachring,eachchildwhopresentlyhasatleast twopieces of candymustpass onepiece to the left, andpass onepiece to the right. Thosechildren who currently have zero or one pieces at that moment will simply sit out that round,waitingfromcandiestotraveltotheirposition.

Same as in other chip-0iring games of this character, the total number of candies remains 0ixedthroughouttheprocess.Asshownin“MathematicsGalore”, JamesTanton’sdelightfulcollectionofrecreationalmathematicalproblemsthatthisproblemwasadaptedfrom,whenevertheinitialstatecontains strictly fewer candies than children, this processwill eventually reach a stable terminalstatewherenochildhasmorethanonepieceofcandy.Giventhe initialdistributionofcandies,thisfunctionshouldreturnthenumberofroundsneededtoreachthisstablestate.

Withmore candies than children, simple applicationof thepigeonholeprinciple proveswhy thisprocesscanneverterminate.However,interestingchaosbreakslooseintheborderlinecasewherethereareexactlyasmanycandiesaschildren!Somestatessuchas[0,3,0] reachastablestatewhileotherssuchas[2,1,0]aredestinedtoraceforeveraroundsomelimitcycleofstatesthatkeep passing the same candy around the circle. It is still an unsolvedmathematical problem toclassify the starting states signi0icantly faster thanmechanistically iterating this process! (Fallingintoalimitcyclecanbedetectedef0icientlywiththefamoustortoiseandharealgorithm,asyouwillseeforyourselfwiththe“Bulgariancycle”problemlaterinthiscollection.)

candies Expectedresult

[1, 0, 1, 1, 0, 1] 0

[3, 0, 0, 0] 1

[4, 0, 0, 0, 0, 1] 6

[5, 1, 0, 0, 0, 0, 0, 1, 0] 10

[0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0] 21

Dibs to dubs

def duplicate_digit_bonus(n):

Someofusascribedeepsigni0icancetonumericalcoincidences,sothatconsecutiverepeateddigitsorotherlowdescriptionlengthpatterns,suchasadigitalclockblinking11:11,seemspecialandpersonallymeaningfultosuchpeople.Theywillthen0indnumberswithrepeateddigitstobemorevaluable than the ordinary numbers that have no obvious patterns. For example, getting into ataxicab0lashinganexcitingnumbersuchas1234or6969wouldbemoreinstatokkablethangettingintoataxicabadornedwithsomemorepedestriannumbersuchas1729.

Assumethatsomesuchpersonassignameaningfulnessscoretoeverypositiveintegersothateverymaximalblockofkconsecutivedigitswithk>1scores10**(k-2)pointsforthatblock.Ablockoftwodigits thusscoresonepoint, threedigitsscore tenpoints, fourdigitsscoreahundredpoints,and so on. However, if only tomake thismore interesting, a special rule is in effect saying thatwheneverablockofdigitsliesatthelowestendofthenumber,thatblockscoresdoublethepointsitwouldscoreinanyotherposition.Thisfunctionshouldcomputethemeaningfulnessscoreofthegivenpositiveintegernasthesumofitsindividualblockscores.

n Expectedresult

43333 200

2223 10

777777777 20000000

3888882277777731 11001

2111111747111117777700 12002

9999997777774444488872222 21210

1234**5678 15418

Nearest smaller element

def nearest_smaller(items):

Givenalistofintegeritems,createandreturnanewlistofequallengthsothateachelementhasbeen replacedwith the nearest element in the original listwhose value is smaller. If no smallerelements exist because that element was the minimum of the original list, that element shouldremain as it is in the result list. If two smaller elements exist equidistant inbothdirections, thisfunctionshouldresolvethisambiguitybyalwaysusingthesmallerofthesetwoelements.

Sidequestionforanycombinatoricsenthusiasts:startingfromarandompermutationofndistinctelements,whatistheexpectednumberofroundsthattheabovealgorithmneedstobeiteratedforallelementstobecomeequal?

items Expectedresult

[42, 42, 42] [42, 42, 42]

[42, 1, 17] [1, 1, 1]

[42, 17, 1] [17, 1, 1]

[6, 9, 3, 2] [3, 3, 2, 2]

[5, 2, 10, 1, 13, 15, 14, 5, 11, 19, 22]

[2, 1, 1, 1, 1, 13, 5, 1, 5, 11, 19]

[1, 3, 5, 7, 9, 11, 10, 8, 6, 4, 2]

[1, 1, 3, 5, 7, 9, 8, 6, 4, 2, 1]

Interesting, intersecting

def squares_intersect(s1, s2):

Anaxis-alignedsquareonthetwo-dimensionalplanecanbede0inedasatuple(x, y, r)where(x, y)arethecoordinatesofitsbottomleftcornerandristhelengthofthesideofthesquare.Giventwosquaresastuples(x1, y1, r1)and(x2, y2, r2),thisfunctionshoulddeterminewhetherthesetwosquaresintersectbyhavingatleastonepointincommon,evenifthatonepointisthesharedcornerpointoftwosquaresplacedkittycorner.(Theintersectionoftwosquarescanhave zero area, if the intersection consists of parts of the one-dimensional edges.) This functionshouldnotcontainanyloopsorlistcomprehensionsofanykind,butshouldcomputetheresultusingonlyintegercomparisonsandconditionalstatements.

Thisproblemshowcasesanideathatcomesupwithsomeproblemsofthisnature;itisactuallyfareasiertodeterminethatthetwoaxis-alignedsquaresdonotintersect,andnegatethatanswer!Twosquaresdonotintersectifoneofthemendsinthehorizontaldirectionbeforetheotheronebegins,orifthesamethinghappensintheverticaldirection.(Thistechniquegeneralizesfromrectangleslyingonthe0lattwo-dimensionalplanetonotonlythree-dimensionalcuboids,buttohyper-boxesofarbitrarilyhighdimensions.)

s1 s2 Expectedresult

(2, 2, 3) (5, 5, 2) True

(3, 6, 1) (8, 3, 5) False

(8, 3, 3) (9, 6, 8) True

(5, 4, 8) (3, 5, 5) True

(10, 6, 2) (3, 10, 7) False

(3000, 6000, 1000) (8000, 3000, 5000) False

(5*10**6, 4*10**6, 8*10**6)

(3*10**6, 5*10**6, 5*10**6)

True

So shall you sow

def oware_move(board, house):

TheAfricanboardgameofOwareisoneofthemostpopularMancalavariations.Afterappreciatingthesimplegeneralstructureofsowinggamesthatallowustotoywithemergentcomplexitywithminimalequipmentofholesandstonesthatareamplyavailableinallplacesonthisplanetthatthehuman handwould ever voluntarily set down its foot, wewill 0irst display heartymathematicalgustobygeneralizingthegamemechanicsforarbitrarynumberofkhouses.Thecompleteminimaxalgorithm to 0ind thebestmove in thegiven situationwill have towaituntilCCPS721Arti+icialIntelligence.However,we alreadyhave themeans to implement a small but essential part of thisalgorithm;themoveexecutortoactoutthegivenmoveinthegivensituation.

Theboardisalistwith2kelements,the0irstkrepresentingthehousesofthecurrentplayerandthelastkrepresentingthoseofheropponent.(Thestoresthatkeeptrackofthecapturedstonesdonotappearanywhereinthis list.)This functionshouldreturntheoutcomeofpickinguptheseedfrom the givenhouse on your side (numbering of houses starting from zero) and sowing theseseedcounterclockwisearoundtheboard.Theoriginalhouseisskippedduringsowing,shoulditoriginallyhaveheldenoughseedtomakethissowingreacharoundafulllap.

After sowing, capturing commences from the house that the last seedwas sown into. Capturingcontinuesbackwardsas longas the currenthouse ison theopponent’s sideandcontains twoorthree seed. For simplicity, we ignore the edge situations from the grand slam rule and thegentlemanlymeta-ruletoalwaysleaveatleastoneseedfortheopponenttomove.

board house Expectedresult

[0, 2, 1, 2] 1 [0, 0, 0, 0]

[2, 0, 4, 1, 5, 3] 0 [0, 1, 5, 1, 5, 3]

[4, 4, 4, 4, 4, 4, 4, 4] 2 [4, 4, 0, 5, 5, 5, 5, 4]

[10, 10, 10, 10] 0 [0, 14, 13, 13]

[4, 10, 4, 1, 1, 1, 4, 4] 1 [5, 0, 6, 3, 0, 2, 5, 5]

[4, 5, 1000, 1, 2, 3] 2 [204, 205, 0, 201, 202, 203]

[0, 0, 0, 6, 1, 1, 2, 1, 2, 1]

3 [0, 0, 0, 0, 2, 0, 0, 0, 0, 0]

That's enough of you!

def remove_after_kth(items, k=1):

Givena listofitems, someofwhichmaybeduplicated, this functionshouldcreateandreturnanew list that isotherwise the sameasitems, butonlyup tok occurrencesof eachelementarekept,andalloccurrencesofthatelementafterthe0irstkarediscarded.

Hint:loopthroughtheitems,maintainingadictionarythatremembershowmanytimesyouhavealreadyseeneachelement.Updatethiscountasyougo,andappendeachelementtotheresultlistonlyifitscountisstillatmostequaltok.

Notethecounterintuitiveandyetcompletelylegitimateedgecaseofk==0thathasthewellde0inedandunambiguouslycorrectanswerofanempty list!Onceagain,anoftenmissedandyet soveryimportantpartofbecomingaprogrammerislearningtoperceivezeroasanumber...

items k Expectedresult

[42, 42, 42, 42, 42, 42, 42] 3 [42, 42, 42]

['tom', 42, 'bob', 'bob', 99, 'bob', 'tom', 'tom', 99]

2 ['tom', 42, 'bob', 'bob', 99, 'tom', 99]

[1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]

1 [1, 2, 3, 4, 5]

[1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5]

3 [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 1, 5]

[42, 42, 42, 99, 99, 17] 0 []

Brussel's choice

def brussels_choice_step(n, mink, maxk):

Thisproblemisadaptedfromanotherjovialvideo"TheBrussel'sChoice"ofNumberphile,asitesoBritishthatyoujustknowtheremustbeaTrevorandaColinsomewhere.Youshouldwatchits0irst0iveminutestogetanideaofwhatisgoingon,evenifthemathematicalpropertiesofsuchnumbersisnotnecessary foryou tocomplete thecoding. (Thenice thingaboutnot justcomputingbutallmachine is that how they work from the point of view of an outsider does not require yourconsciousknowledgeofwhytheyworkontheinside.)Thisfunctionshouldcomputethelistofallnumbersthatthepositiveintegerncanbeconvertedtobytreatingitasastringandreplacingsomesubstringmofitsdigitswiththenewsubstringofeither2*morm/2,thelattersubstitutionallowedonlywhenmisevensothatdividingitbytwoproducesaninteger.

Thisfunctionshouldreturnthelistofnumbersthatcanbeproducedfromninasinglestep.Tokeeptheresultsmoremanageable,wealsoimposeanadditionalconstraintthatthenumberofdigitsinthechosensubstringmmustbebetweenminkandmaxk,inclusive.Thereturnedlistmustcontainthesenumbersinascendingsortedorder.

n mink maxk Expectedresult

42 1 2 [21, 22, 41, 44, 82, 84]

1234 1 1 [1134, 1232, 1238, 1264, 1434, 2234]

1234 2 3 [634, 1117, 1217, 1268, 1464, 1468, 2434, 2464]

88224 2 3 [44124, 44224, 84114, 84124, 88112, 88114, 88212, 88248, 88444, 88448, 176224, 176424, 816424,816444]

123456789 7 9 [61728399, 111728399, 126913578, 146913569, 146913578, 246913489, 246913569, 246913578]

123456789 1 9 (alistwith65elements,thelastthreeofwhichare[1234567169, 1234567178, 1234567818])

Cornered cases

def count_corners(points):

Ontwo-dimensionalintegergrid,acorneristhreepointsoftheform(x,y),(x,y+h)and(x+h,y)forsomeh>0.Suchpointsformsortofacarpenter'ssquareorachevronpointingsouthwestsothat thepoint (x,y)servesas thetip and(x,y+h)and(x+h,y)de0ine itsaxis-alignedwingsofequallength.Forexample,thepoints(2,3),(2,7)and(6,3)formacornerasx=2,y=3andh=4.On the other hand, the points (2, 3), (2, 1) and (0, 3) do not form a corner, since their grouporientation, albeit well-intentioned but unfortunately facing the wrong way, would give thematchingwithh=-2.Alsonotethatanynumberofcornerscanshareacommonpoint.

Given a list ofpoints sorted by their x-coordinates, ties broken by y-coordinates, this functionshouldcounthowmanycornersaltogetherexistamongthesepoints.Again,thisproblemcouldbesolvedin"Shlemiel"fashionbybruteforcingthroughallthree-elementsubsetsofpoints,eitherthemanlywayofusingthreelevelsofnestedfor-loops,orcallingtheitertools.combinationssequencedecoratorforagoodtime.Instead,youshoulditeratethroughtheindividualpoints(x,y)todetermineiftheycanserveasatipofsomechevron.Sincethex-coordinateoftheupwingisthesameasthatofthetip,theinnerwhile-loopcanexaminepointssequentiallyfromthecurrentpoint.Foreachcandidatepoint(x,y+h)totryasthisupwing,youneedtorapidlydeterminewhethertherightwing(x+h,y)thatcompletesthiscornerisamongtheremainingpoints...

As for the corners themselves and how they relate to each other, a curious theorem sets a hardupperboundtohowmanypointscanbechosenfromann-by-n integergridwithoutcreatinganycorners.Trythisoutforyourselfforsmalln,ifonlytogetthefeelofthetightwiggleroomthatwillsoon see you having painted yourself in yet another corner in the twisty maze of possibilities.Conversely,howmanycornerscouldyoucreatebyplacingnpointsontheplane?

points Expectedresult

[(2, 2), (2, 5), (5, 2)] 1

[(0, 3), (0, 8), (2, 2), (2, 5), (5, 2), (5, 3)]

2

[(1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (3, 3), (4, 3)]

3

[(0, y) for y in range(1000)] +[(x, 999-x) for x in range(1, 1000)]

999

[(x, y) for x in range(200) for y in range(200)]

2646700

Count consecutive summers

def count_consecutive_summers(n):

Likeamajesticwildhorsewaitingfortheruggedherototameit,positive integerscanbebrokendownassumsofconsecutivepositiveintegersinvariousways.Forexample,theinteger42oftenusedasplaceholderinthiskindofdiscussionscanbebrokendownintosuchasuminfourdifferentways:(a)3+4+5+6+7+8+9,(b)9+10+11+12,(c)13+14+15and(d)42.Asthelastsolution(d)shows,anypositiveintegercanalwaysbetriviallyexpressedasasingletonsumthatconsistsofthatintegeralone.Givenapositiveintegern,determinehowmanydifferentwaysitcanbeexpressedasasumofconsecutivepositiveintegers,andreturnthatcount.

Thenumberofwaysthatapositiveintegerncanberepresentedasasumofconsecutiveintegersiscalled itspoliteness, andcanalsobe computedby tallyingup thenumberofodddivisorsof thatnumber. However, note that the linked Wikipedia de0inition includes only nontrivial sums thatconsistofatleasttwocomponents,soaccordingtothatde0inition,thepolitenessof42wouldbe3,not4,duetoitsodddivisorsbeing3,7and21.

Powers of two are therefore the least polite of all numbers. Perhaps these powers being thefundamentalbuildingblocksofallnumbersinbinaryrepresentationalsomadethembelievetheirownhypeandballoonuptobetoobigfortheirbritches.(Fametendstodothateventothemostlevel-headed of us.) As an exercise in combinatorics, how would you concisely characterize theoppositeextremeof“mostpolite”numbersthatcanberepresentedassumsofconsecutiveintegersinmorewaysthananynumberlessthanthem?

n Expectedresult

42 4

99 6

92 2

McCulloch's second machine

def mcculloch(digits):

Esotericprogramminglanguagescryouttobeappreciatedasworksofconceptualperformanceart.Thesetarpitsarenotdesignedtoserveaspracticalprogrammingtools,buttopointoutinaha-ha-only-serious manner how some deceptively simple mechanism is secretly some ancient demonswordthatunexpectedlygrantsitswielderthepowersofuniversalcomputation.

IntroducedbyRaymondSmullyaninoneofhisclandestinebrainteasersonlogicandcomputability,McCulloch'ssecondmachineisastringrewritingsystemthatreceivesastringofdigitsbetweenoneandnine.Therewriteruleappliedtotherestofthedigits(denotedbelowbyX)dependsonthe 0irstdigit.Noticehowrule for the leadingdigit2 is applied toX itself,whereas rules for theleading digits 3 to 5 are applied toY computed from the callY=mcculloch(X). This functionshouldreturnNonewhenevereitherXorYisNone.

Formofdigits

Formulafortheexpectedresult (computationaloperation)

2X X quoting

3X Y + '2' + Y concatenationwithseparatormark

4X Y[::-1] reversal

5X Y + Y concatenation

anythingelse None N/A

digits Expectedresult

'329' '929'

'53231' '3123131231'

'4524938' '83948394'

'343424859355' '4859355248593552485935524859355'

'433342717866' '7178662717866271786627178662717866271786627178662717866'

That's enough for you!

def first_preceded_by_smaller(items, k=1):

Findandreturnthe0irstelementofthegivenlistofitems thatisprecededbyatleastk smallerelements in the list. These requiredk smaller elements can be positioned anywhere before thecurrent element, not necessarily consecutively immediately before that element. If no elementsatisfyingthisrequirementexistsinthelist,thisfunctionshouldreturnNone.

Since the only operation performed for the individual items is their order comparison, andespeciallynoarithmeticoccursatanypointduringexecution,thisfunctionshouldworkforlistsofanytypesofelements,aslongasthoseelementsarepairwisecomparablewitheachother.

items k Expectedresult

[4, 4, 5, 6] 2 5

[42, 99, 16, 55, 7, 32, 17, 18, 73] 3 18

[42, 99, 16, 55, 7, 32, 17, 18, 73] 8 None

['bob', 'carol', 'tina', 'alex', 'jack', 'emmy', 'tammy', 'sam', 'ted']

4 'tammy'

[9, 8, 7, 6, 5, 4, 3, 2, 1, 10] 1 10

[42, 99, 17, 3, 12] 2 None

Crab bucket list

def eliminate_neighbours(items):

Givenalistofintegeritemsguaranteedtobesomepermutationofpositiveintegersfrom1tonwherenisthelengthofthelist,keepperformingthefollowingstepuntilthelargestnumberintheoriginallistgetseliminated;Findthesmallestnumberstillinthelist,andremovefromthislistboththatsmallestnumberandthelargeroneofitscurrentimmediateleftandrightneighbours.(Attheedges, you have no choicewhich neighbour you remove.) Return the number of steps needed toremovethelargestelementnfromthelist.Forexample,giventhelist[5, 2, 1, 4, 6, 3],startbyremovingtheelement1anditscurrentlargerneighbour4,resultingin[5, 2, 6, 3].Thenextstepwillremove2anditslargerneighbour6,reachingthegoalintwosteps.

Removinganelementfromthemiddleofthelistisexpensive,andwillsurelyformthebottleneckinthe straightforward solution of this problem. However, since the items are known to be theintegers1ton, itsuf0icestomerelysimulate theeffectoftheseexpensiveremovalswithouteveractuallymutatingitems!De0inetwoauxiliarylistsleft andright tokeeptrackofthecurrentleft neighbour and the current right neighbour of each element. These two lists can be easilyinitializedwithasingleloopthroughthepositionsoftheoriginalitems.

Toremovei,makeits leftandrightneighboursleft[i] andright[i] 0iguratively joinhandswith two assignments right[left[i]]=right[i] and left[right[i]]=left[i], as in“Joe,meetMoe;Moe,meetJoe”.Thisnoblelawofhatchet,axeandsawkeepstheeliminationtimesequalforalltrees,regardlessoftheiroriginalstandingintheforest.(Notree,noproblem;allwillultimatelybeequalinthemulchfromtheequalbiteofthewoodchipper.)

items Expectedresult

[1, 6, 4, 2, 5, 3] 1

[8, 3, 4, 1, 7, 2, 6, 5] 3

[8, 5, 3, 1, 7, 2, 6, 4] 4

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5

range(1, 10001) 5000

[1000] + list(range(1, 1000)) 1

What do you hear, what do you say?

def count_and_say(digits):

Givenastringofdigitsthat isguaranteedtocontainonlydigitcharacters from'0123456789',readthatstring“outloud”bysayinghowmanytimeseachdigitoccursconsecutivelyinthecurrentbunchof digits, and then return the string of digits that you just said out loud. For example, thedigits'222274444499966'wouldreadoutloudas“fourtwos,oneseven,0ivefours,threenines,twosixes”,combinedtoproducetheresult'4217543926'.

As silly and straightforward as this "count-and-say sequence" problem might initially seem, itrequired the genius of no lessermathematician than JohnConwayhimself not only tonotice thetremendous complexity ready to burst out from inches below the surface, but also capture thatwholemessintoasymbolicpolynomialequation,asthemanhimselfexplainsinthisNumberphilevideo. Interested students can also check out the related construct of the in0initely long and yetperfectly self-describingKolakoski sequencewhere only the lengths of each consecutive block ofdigitsiswrittenintotheresultstring,nottheactualdigits.

digits Expectedresult

'333388822211177' '4338323127'

'11221122' '21222122'

'123456789' '111213141516171819'

'777777777777777' '157'

'' ''

'1' '11'

Bishops on a binge

def safe_squares_bishops(n, bishops):

The generalized n-by-n chessboard has this time been taken over by some bishops, eachrepresentedasa tuple(row, col) of thecoordinatesof thesquarethat thebishopstandson.Same as in the earlier version of this problemwith rampaging rooks, the rows and columns arenumberedfrom0ton-1.Unlikeachessrookwhosemovesareaxis-aligned,achessbishopcoversall squares that are on the samediagonal with that bishop arbitrarily far along any of the fourdiagonalcompassdirections.Giventheboardsizen andthelistofbishops onthatboard,countthenumberofsafesquaresthatarenotcoveredbyanybishop.

Tocheckwhethertwosquares(r1, c1)and(r2, c2)arereachablefromeachotherinasinglebishop move, the expression abs(r1-r2)==abs(c1-c2) checks that the horizontal distancebetween those squares equals their vertical distance, which is both necessary and suf0icient forthose squares to lie on the same diagonal. This way you don't have to separately rewrite theessentiallyidenticalblockoflogicfourtimes,butonetesthandlesfourdiagonalsinoneswoop.

n bishops Expectedresult

10 [] 100

4 [(2, 3), (0, 1)] 11

8 [(1, 1), (3, 5), (7, 0), (7, 6)] 29

2 [(1, 1)] 2

6 [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] 18

100 [(row, (row*row) % 100) for row in range(100)] 6666

Dem’s some mighty tall words, pardner

def word_height(words, word):

The lengthofaword iseasyenough tode0ineby tallyingup its characters.Taking theroad lesstraveled,wede0inetheheightofthegivenword witharecursiverulefortheheightofthegivenwordtofollowfromtheheightsoftwowordswhoseconcatenationitis.

First,anycharacterstringthatisnotoneoftheactualwordsautomaticallyhaszeroheight.Second,anactualwordthatcannotbebrokenintoaconcatenationoftwononemptyactualwordshastheheightofone.Otherwise,theheightofanactualwordequalsoneplusthelargeroftheheightsofthetwoactualwordswhosecombinedconcatenationitcanbeexpressedas.Tomaketheseheightsunambiguous for words that can be split into two non-empty subwords in multiple ways, thissplittingisdonethebestwaythatproducesthetallest0inalheight.

Sincethelistofwordsisknowntobesorted,youcanusebinarysearch(availableasthefunctionbisect_left inthebisect module)toquicklydeterminewhethersomesubwordisanactualword.Bemindfulofthereturnvalueofthatfunctionwhenevertheparameterstringisnotanactualword,andalsotheedgecaseofsubwordsthatstartwithtwoormorecopiesoftheletterz.

In thegiantwordlistwords_sorted.txt every individual letter seem tobeawordof itsown,whichmakesthesewordheightsmuchlargerthanweexpectthemtobe.Narrowingthedictionarytocoveronlyeverydaywordswouldmakemostofthesewordheightstopple.Finally,wordssuchas'mankind' steadfastly thumb their noses at humanity by splitting only into nonsense such as'mank'and'ind'.Themeaningofthosewordsisamystery,andthat’swhysoismankind...

word Expectedresult(usingthewordlistwords_sorted.txt)

'hxllo' 0

'chukker' 1

'asteroid' 7

'pedicured' 2

'enterprise' 6

'antidisestablishmentarianism' 11

'noncharacteristically' 13

Up for the count

def counting_series(n):

TheChampernowneword1234567891011121314151617181920212223...,alsoknownasthecountingseries,isanin0initelylongstringofdigitsmadeupofallpositiveintegerswrittenoutinascendingorderwithoutanyseparators.ThisfunctionshouldreturnthedigitatpositionnoftheChampernowneword.Positioncountingagainstartsfromzeroforusbuddingcomputerscientists.

Ofcourse,theautomatedtesterwillthrowatyourfunctionvaluesofnhugeenoughthatthosewhoconstruct theChampernownewordasanexplicit stringwill runoutofboth timeandspace longbeforereceivingtheanswer.Instead,notehowthefractalstructureofthisin0initesequencestartswith 9 single-digit numbers, followed by 90 two-digit numbers, followed by 900 three-digitnumbers,andsoon.Thisobservationgiftsyouapairofsevenleaguebootsthatallowtheirwearerskippre0ixesofthisseriesinexponentialleapsandbounds,insteadofhavingtocrawltheirwaytothedesiredpositionone step at the timewith the rest of us.Onceyou reach theblockofk-digitnumbers that contains the positionn, the digit there is best determinedwith integer arithmetic,perhapsaidedbyanstrconversionforaccesstodigitpositions.

Thisfavouriteproblemofmanypaststudentsseguesintoamoredif0icultbutalsomorerewardingsidequest.De0ine“shy”integersasthosethatappearinsidetheChampernownewordforthe0irsttimeat their 0irst “of0icialappearance”,whereas “eager” integersmakeearlierappearances in thedigitsequenceasFrankennumbersstitchedtogetherfrompiecesoflessernumbers.Canyouthinkuparulethatestablishesataglancethattheeight-digitinteger92021222ismuyeager,whereasitsshysuccessor92021223doesnotrevealherfacetotheworldbeforeherquinceañera?

n Expectedresult

0 1

10 0

100 5

10000 7

10**100 6

Revorse the vewels

def reverse_vowels(text):

Given a text string, create and return a new string constructed by 0inding all its vowels andreversing their order, while keeping all other characters exactly as they were in their originalpositions.Tomaketheresultmorepresentable,thecapitalizationofeachpositionmustremainthesameasitwasintheoriginaltext.Forexample,reversingthevowelsof'Ilkka'shouldproduce'Alkki'insteadof'alkkI'.Forthisproblem,vowelsaretheusual'aeiouAEIOU'.

Along with many possible ways to perform this dance, one straightforward way to reverse thevowelsstartsbyappendingthevowelsoftextintoaseparatelist,andinitializingtheresulttoan empty string. Then, loop through all characters of the original text. Whenever the currentcharacter isavowel,pop one fromtheendof the listof thevowels.Convert thatvowel toeitherupper-orlowercasedependingonthecaseofthevowelthatwasoriginallyinthatposition,andaddittoresult.Otherwise,addthecharacterfromtheoriginaltexttotheresultasitwas.

ApplyingthisoperationtoperfectlyordinaryEnglishsentencesoftenproducespiglatinimitationsof other languages. Perhaps some Vietnamese-speaking reader could extend this algorithm torecognizeandreversealsoalldiacriticalversionsofthevowelsinthatlanguage,ifonlytocheckoutwhetherthistransformationyieldssomeunintentionalcomedyorrevelations,divineormundane,whenappliedtoeverydayVietnamesesentences.

text Expectedresult

'Revorse the vewels' 'Reverse the vowels'

'Bengt Hilgursson' 'Bongt Hulgirssen'

'Why do you laugh? I chose the death.'

'Why da yee leogh? I chusa thu dooth.'

'These are the people you protect with your pain!'

'Thisa uro thi peoplu yoe protect weth year peen!'

"Who's the leader of the club that's made for you and me? T-R-I-C-K-Y M-O-U-S-E! Tricky Mouse! TRICKY MOUSE! Tricky Mouse! TRICKY MOUSE! Forever let us hold our Hammers high! High! High! High!"

"Whi's thi liider af thu clob thot's mude fer yeo end mu? T-R-O-C-K-Y M-I-E-S-U! Trocky Miesu! TROCKY MIESU! Trocky Miesu! TROCKY MIESA! Furovor let as hald uer Hommers hagh! Hegh! Hegh! Hogh!"

Everybody on the floor, come do the Scrooge Shuffle

def spread_the_coins(coins, left, right):

Somepositionsontheintegerlineℤinitiallycontaingoldcoins,asgiveninthecoinsliststartingfromtheoriginpositionofzero.Forexample,ifcoins==[3, 0, 1, 7],therearethreecoinsattheposition0,onecoinattheposition2,andsevencoinsattheposition3.Allotherpositionsontheintegerlineℤ,bothpositiveandnegative,areinitiallyempty,asisalsotheposition1inthemiddle.

Anypositionthatcontainsat leastleft+right coinsisunstable.Forexample, ifleft==3 andright==2forthepreviousexamplepiles,onlytheposition3wouldbeunstable.Giventhestartingcon0iguration of coins, your function should repeatedly 0ind some unstable position i. Moveexactlyleftcoinsfromthatpositionitothepositioni-1,andmoveexactlyrightcoinstothepositioni+1.Performingthisspillinthepreviouscon0igurationattheposition3producesthenewcon0iguration[3, 0, 4, 2, 2]thatisstableeverywheresincenopositioncontains0ivecoinsormore,andthisprocessterminates.

Itcanbeproventhattheterminalcoincon0igurationofthisback-and-forthdancewillnecessarilybereachedaftersome0initenumberofsteps,andisuniqueindependentoftheorderthatyouprocesstheunstablepositionsintheinterim.Thisfunctionshouldreturnatuple(start, coins)wherestartistheleftmostpositionthatcontainsatleastonecoin.Thesecondcomponentoftheanswerliststhecoins thatendupineachpositionfromthepositionstart uptothelastpositionthatcontains at least one coin. For example, the expected answer from this function for the previousexamplewouldbe(0, [3, 0, 4, 2, 2]).Someinitialcon0igurationswillendupspillingcoinstothenegativepartoftheintegerlineℤ,soyourfunctionneedstobeabletohandlethis.

coins left right Expectedresult

[0, 0, 2] 1 1 (1, [1, 0, 1])

[20] 3 2 (-4, [3, 1, 4, 2, 4, 2, 4])

[8, 4] 3 2 (-2, [3, 1, 3, 3, 2])

[111, 12, 12] 19 6 (-6, [19, 13, 13, 13, 13, 13, 10, 23, 18])

[101] 1 1 (atuplewhose0irstelementequals-50andthesecondelementisalistof101copiesof1)

Rational lines of action

def calkin_wilf(n)

ThenodesoftheCalkin-Wilftree,whenreadinlevelordersothattheelementsineachlevelareread from left to right, produce the linear sequence of all possiblepositive rational numbers.Almostasifbymagic,thisconstructionguaranteeseverypositiveintegerfractiontoappearexactlyonce in this sequence. Evenmore delightfully, this constructionmakes every rational number tomakeitsappearanceinitslowestreducedform!Toperformthefollowingcalculations,youshouldimportthedatatypesFractionanddequefromthefractionsandcollectionsmodules.

Yourfunctionshouldreturnthen:thelementofthissequence.First,createanewinstanceofdequeandappendthe0irstfraction1/1toprimethepump,sotospeak,toinitiatetheproductionofthevaluesofthissequence.Repeatthefollowingprocedurentimes;popthefractioncurrentlyinfrontofthequeueusingthedeque methodpopleft,extractitsnumeratoranddenominatorp andq,andpush the twonew fractionsp/(p+q) and(p+q)/q to thebackof thequeue, in thisorder.Returnthefractionobjectthatwaspoppedinthe0inalround.

Onceyoureach thepositionn//2+1, thequeuealreadycontains theresultyouneed,soyoucansaveaheftychunkofmemorybynotactuallypushinginanynewvalues.ThelinkedWikipediapageandothersourcesalsoprovideshortcutstojumpintothegivenpositionfasterthansloughingyourwaytherethehardwayoneelementatatime.

n Expectedresult(asFraction)

10 3/5

10000 11/39

100000 127/713

Verbos regulares

def conjugate_regular(verb, subject, tense):

Conjugating verbs en español is signi0icantly more complex than in English where the sameinformationisconveyedwithanexplicitsubjectandadditionalwordsaroundthatpinchein0initive.Frustrated students can only exclaim “¡Dios mío!” or “¡No me gusta!” and memorize all thesemechanisticforms.AfterobviouslywatchingonetoomanyepisodesofNarcostohelpthelockdowntimegoby,thisauthordecidedtospendsomeofthistryingtimepreparinghimselfforthecomingborderless cyberpunk utopia, and tomo el toro por los cuernos by 0inally learning some basicSpanish,oneofthemostmeme-worthylanguagesdevisedformenandtheirmachines.

Fortunately,regularSpanishverbswhosein0initiveendswitheither-ar,-eror-irfollowsystematicrulesthatmakeagoodexerciseinPythonstringprocessingandmultiwaylogic.Giventhein0initiveoftheverb,thesubjectasoneofyo,tú,él,ella,usted,nosotros,vosotros,ellos,ellasandustedes,andthetense asoneoffoursimpleindicativetensespresente,pretérito,imperfectoandfuturotokeepthisproblemmanageable,thisfunctionshouldreturnthatconjugateoftheverb.Sinceitisnolongertheyear1985wheneveryASCIIcharacterwasstoredinasinglebyte,enoughforourdailyuphilljourneybothwaysrainorshine(andthatishowwelikedit,withoutcomplaining!),today’sUnicodestringsofPython3handleaccentedcharactersnodifferently fromanyothercharacters.Therefore,theseaccentsshouldalsobecorrectinthereturnedanswer.

(Este problema es básicamente un gran árbol de decisiones. Sin embargo, las regularidades en lasreglas de conjugación del español te permiten combinar casos equivalentes paramanejarlos con lamismalógica.Suescaladedecisionesdebecontenermuchomenosdecientoveinteescalones.)

verb subject tense Expectedresult

'añadir' 'ellos' 'presente' 'añaden'

'cantar' 'yo' 'presente' 'canto'

'bailar' 'tú' 'pretérito' 'bailaste'

'decidir' 'usted' 'futuro' 'decidirá'

'meter' 'ustedes' 'imperfecto' 'metían'

'romper' 'ella' 'pretérito' 'rompió'

'escribir' 'nosotros' 'imperfecto' 'escribíamos'

Hippity hoppity, abolish loopity

def frog_collision_time(frog1, frog2):

Afroghoppingalongonthein0initetwo-dimensionalgridofintegersisrepresentedwitha4-tupleoftheform(sx,sy,dx,dy)sothat(sx,sy)isthefrog'sstartingpositionatthetimezero,and(dx,dy) is its constant direction vector for each successive hop. Time advances in discreteintegerstepssothateachfrogmakesonehopateverytickoftheclock.Attimet, thepositionofthatfrogisgivenbytheformula(sx+t*dx,sy+t*dy)thatcanbenimblyevaluatedforanyt.

Giventwofrogsfrog1 andfrog2 thatinitiallystandondifferentsquares,returnthetimewhenbothfrogshopintothesamesquare.Ifthesetwofrogsneverhopintothesamesquareatthesametime,thisfunctionshouldreturnNone.

This function should not contain any loopswhatsoever, but result should be computedwithconditional statements and integer arithmetic. First solve the simpler version of this problem ofone-dimensional frogs restricted tohopalong theone-dimensional lineof integers.Onceyougetthatfunctionworkingcorrectly,includingallitspossibleedgecasessuchasbothfrogsjumpingattheexactsamespeed,oroneorbothfrogsstayingputinthesameplacewithzerospeed,useyourone-dimensionalmethodasasubroutinetosolvefortseparatelyforthex-andy-dimensionsintheoriginalproblem.Combinethesetwoone-dimensionalanswerstogetthe0inalanswer.

frog1 frog2 Expectedresult

(0, 0, 0, 2) (0, 10, 0, 1) 10

(10, 10, -1, 0) (0, 1, 0, 1) None

(0, -7, 1, -1) (-9, -16, 4, 2) 3

(-28, 9, 9, -4) (-26, -5, 8, -2) None

(-28, -6, 5, 1) (-56, -55, 9, 8) 7

(620775675217287, -1862327025651882, -3, 9)

(413850450144856, 2069252250724307, -2, -10)

206925225072431

Where no one can hear you bounce

def reach_corner(x, y, n, m, aliens):

A lone chessbishop 0indshimself standingon the square(x,y) of a curiousn-by-m chessboard0loating in theouter space, coveredwith completely frictionlessmagic ice. (True story. Yeah, andonceagain,zero-basedindexing.)Thisboardisnotnecessarilysquare,butcanbeanyrectangleofinteger dimensions. The board is surrounded from all sides with bouncywalls similar to an airhockeytable.Someofthesquaresontheboardarealiensthatuseboththeirbigmouthsandlittlemouthstomakeitgameoverforanymanwhoenters.

Rapidmotionknife trickswon'thelp thebishophere.Hemust instead reachanyoneof the fourpossibleexitsatthefourcornersoftheboard.SimilartopatientlywatchingthescreensaverofanoldDVDplayer, thebishopmustreachanyoneof thesecorners inasinglemove.Thebishopcaninitiallypropelhimselftoanyofthefourdiagonaldirections.Afterthisinitialimpulsethatgetshimgoing,thebishopcannolongercontrolhismovementsonthefrictionlessice,butwillkeepslidingtowardswhateverendthepresentdirectionvectorandbouncingfromthewallstakehim.Itisevenpossible for the bishop to forever repeat the same cycle of squares. (Your function, unknowinglydoing this dance on the far more complex surface of computer state con0igurations, should notfollowsuit,butnukethewholecomputationfromtheorbit,justtobesure.)

This functionshoulddeterminewhether thereexistsat leastonestartingdirection that leads thebishoptothesafetyofanyoneofthefourcorners,avoidingallthealiensalongtheway.

x y n m aliens Expectedresult

0 2 5 5 [] False

4 4 9 9 [(0, 0), (0, 8), (8, 0), (8, 8)] False

1 1 1000 2 [(0, 0), (0, 1), (999, 0)] True

1 1 1000 2 [(0, 0), (0, 1), (999, 1)] False

3 2 4 4 [(1, 2), (0, 1)] False

3 2 5 4 [(2, 2), (1, 4)] True

Nearest polygonal number

def nearest_polygonal_number(n, s):

Anypositive integers>2de0inesan in0initesequenceofs-gonalnumberswhose i:thelement isgivenbytheformula((s-2)i2-(s-4)i)/2,asexplainedontheWikipediapage"PolygonalNumber".Inthisformulathatobviouslywasnotdevisedbysomecomputerscientistbutamorenormalperson,positionsstartfrom1,not0.Furthermore,werewrotetheformulatousetheletteritodenotetheposition,sincetheletternalreadymeanssomethingelseforusinthisproblem.

Forexample,thesequenceof"octagonalnumbers"thatspringsforthfroms=8shootsintoin0inityas 1, 8, 21, 40, 65, 96, 133, 176... Given the number of sidess and an arbitrary integern, thisfunctionshouldreturnthes-gonalintegerclosestton.Ifnfallsexactlyhalfwaybetweentwos-gonalnumbers,returnthesmallerone.

Asyoucanseefromthelastrowoftheexpectedresultstable,thisfunctionmustbeef0icientevenforgargantuanvaluesofn.Youshouldharnessthepowerofrepeatedhalvingtopullyourwagontothispromisedlandwithacleverapplicationofbinarysearch.Startwithtwointegersa andbwide enough that they satisfya<=i<=b for the currently unknown positioni that the nearestpolygonalnumberisstoredin.(Justinitializetheseasa=1andb=2,andkeepsquaringbuntilthes-gonal number in that position gets too big. It's not like these initial bounds need to be superaccurate.)Fromthere,computethemidpointposition(a+b)//2,andlookattheelementinthatposition. Depending on how that midpoint element compares to n, bring either b or a to themidpointposition.Continue thisuntil thegaphasbecomesmallenoughso thatb-a<2, atwhichpointone0inalcomparisontellsyouthecorrectanswer.

n s Expectedresult

5 3 6

27 4 25

450 9 474

10**10 42 9999861561

10**100 91 10000000000000000000000000000000000000000000000000416332753518329478897755794704334003003544212420356

Don’t worry, we will fix it in the post

def postfix_evaluate(items):

Whenarithmeticexpressionsaregiveninthefamiliarin<ixnotation2+3*4,parenthesesnudgethedifferentevaluationordertodiffer fromtheusualPEMDASorderdeterminedbyprecedenceandassociativityofeachoperator.Thealternativepost<ixnotation(alsoknownasReversePolishNotation,forallyou“simplePolesonacomplexplane”)may0irstlookweirdtopeopleaccustomedto the conventional in0ix. However, post0ix notation turns out to be easier formachines, since itallowsencodinganyintendedevaluationorderwithoutanyparentheses!

Apost0ixexpressionisgivenasalistofitemsthatcanbeeitherindividualintegers,oroneofthestrings'+','-','*'and'/'todenotethefourbasicarithmeticoperators.Toevaluateapost0ixexpressionusingasimplelinearloop,useanordinarylistasaninitiallyemptystack.Loopthroughtheitemsonebyone,fromlefttoright.Wheneverthecurrentitemisaninteger,justappendittothe endof the list.Whenever the current item isoneof the four arithmeticoperations,pop twoitemsfromtheendofthelisttoperformthatoperationon,andappendtheresultbacktothelist.Assumingthatitemsisalegalpost0ixexpression,whichisguaranteedinthisproblemsothatyoudon'tneedtoperformanyerrordetectionorrecovery,onceallitemshavebeenprocessed,thelonenumberleftinthestackbecomesthe0inalanswer.

Toavoidtheintricaciesof0loatingpointarithmetic,youshouldperformthedivisionoperationusingthePythonintegerdivisionoperator// thattruncatestheresulttotheintegerpart.Furthermore,toavoidthecrashfromdividingbyzero,thisproblemcomeswithanarti0icial(yetmathematicallyperfectlysound)rulethatdivisionbyzerogivesazeroresult,insteadofcrashing.

(By addingmore operators and another auxiliary stack, an entire Turing-complete programminglanguagecanbebuiltaroundpost0ixevaluation.InterestedstudentscansallyforthtotheWikipediapage"Forth"tolearnmoreofthisingeniouslysimpleconcatenativeprogramminglanguage.)

items (equivalentin0ix) Expectedresult

[2, 3, '+', 4, '*'] (2+3)*4 20

[2, 3, 4, '*', '+'] 2+(3*4) 14

[3, 3, 3, '-', '/', 42, '+'] 3/(3-3)+42 42

[7, 3, '/'] 7/3 2

[1, 2, 3, 4, 5, 6, '*', '*', '*', '*', '*']

1*2*3*4*5*6 720

Fractran interpreter

def fractran(n, prog, giveup=1000):

ThelategreatJohnConwayisbestknownforTheGameofLife,nottobeconfusedwiththeearlierfamilyboardgameofthesamename.SincethatachievementeclipsedbasicallyallotherwackyandoriginalcreationsofConway,weoughttorectifythisbygivingtheselessappreciatedcreationsanoccasionalspininthepaparazzilightsandtheredcarpetfame.

ThisfunctionworksasaninterpreterfortheesotericprogramminglanguagecalledFRACTRAN,apun combining “fraction” with the FORTRAN programming language. (Things used to be all inuppercasebackinwhenrealscientistsworehorn-rimmedglassescametoworkdrivingcarswereequippedwith tail 0ins,withoccasionaldollarsigns interspersedasvisual separators tokeep theperfumed princes of the military-industrial complex happy.) A program written in such veryesoteric form consists list of positive integer fractions, in this problem given as tuples of thenumerator and the denominator. Of course, you are notmerely allowed but required to use theFractiondatatypeinthefractionsmoduletoperformthesecomputationsexactly.

Givenapositive integern as itsstartstate, thenextstate istheproductn*f forthe0irst fractionlistedinprog forwhichn*f isanexactinteger.Thatintegerthenbecomesthenewstateforthenext round. Oncen*f is not an integer for any of the fractionsf listed inprog, the executionterminates. Your function should compute the sequence of integers produced by the givenFRACTRANprogram,withaforcedtermina...(“Oi,m8,Ol’ConniewasBritish!”),sorry,forcedhaltingtakingplaceaftergiveupsteps,shouldtheexecutionhavenothaltedbyitselfbythen.

n prog giveup Expectedresult

3 [(94, 51)] 10 [3]

7 [(7, 3), (12, 7)] 10 [7, 12, 28, 48, 112, 192, 448, 768, 1792, 3072, 7168]

10 [(3, 6), (9, 11), (4, 5), (6, 2), (7, 1)]

10 [10, 5, 4, 2, 1, 3, 9, 27, 81, 243, 729]

5 [(108, 125), (90, 45), (122, 57), (75, 158)]

10 [5, 10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120]

Permutation cycles

def permutation_cycles(perm):

In this problem, apermutation is a list ofn elements that contains every integer from0 ton-1exactlyonce.Forexample,[5, 2, 0, 1, 4, 3]isoneofthe6!=720permutationsforn=6.Eachpermutationcanbe consideredabijective function thatmaps eachposition from0 ton-1into some unique position so that no two positionsmap to the same position. For example, thepreviouspermutationmapstheposition0into5,position1into2,2into0,andsoon.

AsexplainedintheYouTubevideo"CycleNotationofPermutations"ofSocratica,acycleisalistofpositionssothateachpositionismappedintothenextpositioninthecycle,withthelastelementlooping back to the 0irst position of that cycle. Positions inside a cycle are treated in a cyclic"necklace"fashionsothat[1, 2, 3],[2, 3, 1]and[3, 1, 2]arerotationallyequivalentways to represent the same three-cycle, distinct from another possible cycle of these elementsrepresentableaseither[1, 3, 2],[3, 2, 1]or[2, 1, 3].Toconstructthecyclethatthepositionibelongsto,startatthatpositionj=iandkeepmovingfromthecurrentpositionjtoitssuccessor positionperm[j] until you return to the original positioni. The cycles of the abovepermutationare[0, 5, 3, 1, 2] and[4],thesecond“unicycle”beingasingletonasthispermutationmapstheposition4backintoitself.

Thisfunctionshouldlisteachindividualcyclestartingfromitshighestelement,andthecyclesmustbe listed in increasingorderof their startingpositions.Forexample, thepreviousexamplecycles[4] and[5, 3, 1, 2, 0] mustbelistedinthisorder,since4<5.Furthermore,insteadofreturninga listofcycles, thesecyclesmustbeencodedasa <lat list thatsimplyrattlesoff thesescycleswithoutanyseparatorsinbetween.Amazingly,thisrun-onstandardrepresentationofthepermutationstillallowsuniquereconstructionoftheoriginalpermutationanditscycles!

perm Expectedresult

[0, 1, 2, 3] [0, 1, 2, 3]

[3, 2, 1, 0] [2, 1, 3, 0]

[5, 2, 0, 1, 4, 3] [4, 5, 3, 1, 2, 0]

[2, 4, 6, 5, 3, 1, 0] [5, 1, 4, 3, 6, 0, 2]

[5, 3, 0, 1, 4, 2, 6] [3, 1, 4, 5, 2, 0, 6]

[0, 9, 7, 4, 2, 3, 8, 5, 1, 6] [0, 7, 5, 3, 4, 2, 9, 6, 8, 1]

Whoever must play, cannot play

def subtract_square(queries):

Twoplayersplayagameof"Subtractasquare"startingfromapositiveinteger.Onhisturntoplay,eachplayermustsubtractsomesquarenumber(1,4,9,16,25,36,49,...)fromthecurrentnumbersothattheresultdoesnotbecomenegative.Underthenormalplayconventionofthesegames,theplayerwhogetstomovetozerowinsashisopponentisunabletomove.Thisisanexampleofanimpartialgamewheretheexactsamemovesareavailabletotheplayerwhoseturnitistomove,asopposed to “partisan games” such as chesswhere playersmay onlymove pieces thatwear theircolours.

Thisandsimilarcombinatorialgamescanbemodelledandsolvedwithrecursiveequations.Astateishot(or“winning”)ifatleastonelegalmovefromthatstateleadstoacold(or“losing”)state.Yes,thatreallyistheentirede0inition,includingthebasecase.(Youmighthavetosquintabittoseeit.)

Since theheat valueof each staten is determinedby theheat values of states lower thann,wemightaswellcombinealltheseheatcomputationsofstatesintoasinglebatchjob.Thisfunctionshouldreturna listofresults forthegivenqueries sothatTrue meanshotandFalse meanscold.Youshouldcomputetheheatvaluesofallstatesasasinglelistbuiltupfromlefttoright.Theheat value computation at each state can then read the previously computed heat values of thelowernumberedstatestowhichthereisalegalmovefromthecurrentstate.

(Inthemisèreversionofthegamethathasotherwiseidenticalrulesbutwhereyouwinbylosingtheoriginalgamebygettingtozero,thesede0initionswouldbeadjustedaccordingly.)

queries Expectedresult

[7, 12, 17, 24] [False, False, False, True]

[2, 3, 6, 10, 14, 20, 29, 39, 57, 83, 111, 149, 220, 304, 455, 681]

[False, True, True, False, True, False, True, False, False, True, True, True, True, True, True, True]

[7, 12, 17, 23, 32, 45, 61, 84, 120, 172, 251, 345, 510, 722, 966, 1301, 1766, 2582, 3523, 5095, 7812, 10784, 14426, 20741]

[False, False, False, True, True, True, True, True, True, True, True, False, False, True, True, True, True, True, True, True, True, True, True, True]

ztalloc ecneuqes

def ztalloc(shape):

ThefamousCollatzsequencewasusedinthelecturesasanexamplesituationwhereitisnecessaryto use awhile-loop, since it is impossible to predict in advance howmany steps are needed toreach the goal from the given starting value. (In fact, no 0inite upper bounds are known, as theexistence ofany such upper bound, regardless of how loose and pessimistic,would immediatelyaf0irmtheCollatzconjecture.)Theanswerwasgivenasthelistofintegersthatthesequencevisitsbeforeterminatingatitsgoal.

However,theCollatzsequencecanalsobeviewedinabinaryfashiondependingonwhethereachvaluestepsup(3x+1)ordown(x/2)fromthepreviousvalue,denotingthesestepswith'u' and'd',respectively.Startingfromn=12,thesequence[12, 6, 3, 10, 5, 16, 8, 4, 2, 1]wouldhavethestepshape'ddududddd'.

This functionshould,giventhestepshape asastringmadeof lettersu andd,determinewhichstartingvaluefortheCollatzsequenceproducesthatexactshape.However,thisfunctionmustalsorecognize that some shape strings are impossible as entailed by the Collatz transition rules, andcorrectlyreturnNone forallsuchshapes.Youshouldstartfromthegoalstate1,andperformthegiven transitions in reverse. Along theway, you have ensure that your function does not acceptmovesthatwouldbeillegalintheoriginalforward-goingCollatzsequence.Especiallytherule3x+1canonlybeappliedtooddvaluesofx,nomatterhowtemptingthesuccessor3x+1mightbe.

shape Expectedresult

'ududududddddudddd' 15

'dudududdudddudddd' 14

'uduuudddd' None

'd' 2

'uuududdddduuuuuuudddddd' None

'duuudddddddd' None

The solution solution

def balanced_centrifuge(n, k):

ThisproblemwasinspiredbyyetanotherNumberphilevideo,thistime"TheCentrifugeProblem".Alternatively,studentswhoseeyescanreadfasterthantheirearslistencancheckoutMattBaker'spost"TheBalancedCentrifugeProblem".Acentrifugehasn identicalslots,eachbigenoughto0itonetesttube.Topreventthiscentrifugefromwobbling,kidenticaltubesmustbeplacedintotheseslotssothattheirmutualcenterofgravityliespreciselyatthecenterofthecentrifuge.

Forbalancingktesttubesintonslotstobepossible,bothkandn-kmustbeexpressibleassumsofprimefactorsofn,notnecessarilydistinct.Forexample,whenn equals6withprimefactors2and3,thecentrifugecanhold0,2,3,4(=2+2)or6(=3+3)testtubes.However,thereisnosafewaytobalance1or5testtubesintothesesixslots.Eventhough5=2+3satis0iesthe0irstpartoftherule,thereisnowaytocounterbalancetheremainingemptyslot!

This functiondoesnot actuallyneed to construct thebalanced con0igurationofk test tubes, butdeterminewhethersomebalancedcon0igurationexistsforthegivennandk.

n k Expectedresult

6 3 True

7 0 True

15 8 False

222 107 True

1234 43 False

Reverse ascending sublists

def reverse_ascending_sublists(items):

Createandreturnanewlistthatcontainsthesameelementsastheitemslistargument,butwheretheorderoftheelementsinsideeverymaximalstrictlyascendingsublisthasbeenreversed.Notethemodi0ier“strictly”usedintheprevioussentencetorequireeachelementtobegreaterthanthepreviouselement,notmerelyequaltoit.

Asisthecasewithallfunctionsfoundinthisproblemcollection,thisfunctionshouldnotmodifythecontentsoftheoriginalitemslist,butcreateandreturnabrandnewlistobjectthatcontainstheresult,nomatterhowtemptingitmightbetoperformthisoperationinplaceintheoriginallisttosavememory.Ifyouwanttousetheoriginalitems asthestartingpointofcomputation,youcanalwaysassignitems=items[:] in the 0irst lineofyour function to createa separatebutequalcopyoftheitems,tooperateonthatcopyinsteadoftheoriginalfromthatpointonwards.

Inthetablebelow,differentcolourshighlightthemaximalstrictlyascendingsublistsforreadability,andarenotpartoftheactualargumentobjectgiventothePythonfunction.

items Expectedresult

[1, 2, 3, 4, 5] [5, 4, 3, 2, 1]

[5, 7, 10, 4, 2, 7, 8, 1, 3] [10, 7, 5, 4, 8, 7, 2, 3, 1]

[5, 4, 3, 2, 1] [5, 4, 3, 2, 1]

[5, 5, 5, 5, 5] [5, 5, 5, 5, 5]

[1, 2, 2, 3] [2, 1, 3, 2]

Brangelin-o-matic for the people

def brangelina(first, second):

The task of combining the 0irst names of beloved celebrity couples into a catchy shorthand formedia consumption turns out to be simple to automate. Start by counting how many maximalgroups of consecutive vowels (aeiou, as to keep this problem simple, the letter y is always aconsonant)exist insidethe0irstname.Forexample,'brad' and'jean' haveonevowelgroup,'jeanie'and'britain'havetwo,and'angelina'and'alexander'havefour.Notethatavowelgroupcancontainmorethanonevowel,asintheword'queueing'withanentire0iver.

Ifthe0irstnamehasonlyonevowelgroup,keeponlytheconsonantsbeforethatgroupandthrowawayeverythingelse.Forexample,'ben'becomes'b',and'brad'becomes'br'.Otherwise,ifthe0irstwordhasn>1vowelgroups,keepeverythingbeforethesecondlastvowelgroupn-1.Forexample,'angelina'becomes'angel'and'alexander'becomes'alex'.Concatenatethatwiththestringyougetbyremovingallconsonantsfromthebeginningofthesecondname.All0irstand second names given to this function are guaranteed to consist of the 26 lowercase Englishlettersonly,andeachnamewillhaveatleastonevowelandoneconsonantsomewhereinit.

Theserulesdonotalwaysproducethebestpossibleresult.Forexample,'ross' and'rachel'combineinto'rachel'insteadofthemoreinformative'rochel'.Thereadercanlaterthinkupmoreadvancedrules thatcoverawidervarietyofnamecombinationsandspecial cases. (A trulyadvancedsetof rules,perhaps trainedwithdeep learning techniques to implicitly recognize thesemantic content might combine 'donald' and 'hillary' into either 'dollary' or'dillary',dependingontheintendedtoneandaudience.)

first second Expectedresult

'brad' 'angelina' 'brangelina'

'angelina' 'brad' 'angelad'

'sheldon' 'amy' 'shamy'

'amy' 'sheldon' 'eldon'

'frank' 'ava' 'frava'

'britain' 'exit' 'brexit'

Line with most points

def line_with_most_points(points):

Apointonthetwo-dimensionalintegergridℤ2isgivenasatwo-tupleofx-andy-coordinates,forexample(2,5)or(10,1).AsoriginallypostulatedbyEuclid,anytwodistinctpointsontheplanede0ineexactlyonelinethatgoesthroughbothpoints.(Indifferentlyshapedspacesmadeof0inger-quotes “points” and “lines”, different rules and their consequences apply.) Of course, this uniqueline,beingshamelesslyin0initetobothdirections,willalsopassthroughanin0initenumberofotherpointsonthatsameplane,althoughthatclaimmightnotbeaseasytoprovefrom0irstprinciples.

Given a list ofpoints on the grid of integers, 0ind the line that contains the largest number ofpointsfromthislist.Toguaranteetheuniquenessoftheexpectedresultforthepseudorandomfuzztesting,thisfunctionshouldnotreturnthelineitself,butmerelythecountofhowmanypointslieonthatline.Thelistofpoints isguaranteedtocontainatleasttwopoints,andthatallitspointsaredistinct,butotherwisethesepointsarenotgiveninanyspeci0icorder.

Togetstarted,consulttheexampleprogramgeometry.pyforthecrossproductfunctionthatcanbe used to quickly determinewhether three given points on the plane are collinear. Using thisoperationasasubroutine,therestofthealgorithmcanoperateatahigherlevelofabstraction.

This problem could always be inef0iciently brute forced with three nested loops, but the point(heh)of thisproblem isnot todo toomuchmorework thanyoureallyneed to.Armedwith thisfunction,youcouldnextnumericallyinvestigatetheproblempresentedinthemiddlepanelofthisXKCDcomic.(Whengeneratingeachrandomnon-self-intersectingpath,rejectionsamplingwouldbetheeasiestwaytoensurethatyourchoicesamongallpossiblesuchpathsareunbiased.)

points Expectedresult

[(42, 1), (7, 5)] 2

[(1, 4), (2, 6), (3, 2), (4, 10)] 3

[(x, y) for x in range(10) for y in range(10)] 10

[(3, 5), (1, 4), (2, 6), (7, 7), (3, 8)] 3

[(5, 6), (7, 3), (7, 1), (2, 1), (7, 4), (2, 6), (7, 7)] 4

Om nom nom

def cookie(piles):

ThebelovedCookieMonsterfromSesameStreethasstumbleduponatablewithpilesofcookies,eachpileapositiveinteger.However,themonomaniacalobsessivenessoftheCountwhosetupthis0iestahasrecentlyescalatedtoawholenewlevelofseverity.TheCount insiststhatthesecookiesmustbeeateninthesmallestpossiblenumberofmoves.Eachmovechoosesoneoftheremainingpilesizesp,andremovespcookiesfromeverypilethatcontainsatleastpcookies(thuseradicatingallpileswithexactlypcookies),andleavesallsmallerpilesuntouchedastheywere.

SincetheCountisalsounhealthilyobsessedwithorderandhierarchies,heexpectsthesemovestobe done in decreasing order of values ofp, as seen in the third column of the table below. Thisfunction should return the smallest number ofmoves that allows CookieMonster to scarf downthese cookies. For the given piles, your function should loop trough its possible moves, andrecursivelysolvetheproblemforthenewpilesthatresultfromapplyingeachmovetopiles.Theoptimalsolutionforpilesisthensimplytheoptimaloneofthosesubproblemsolutions,plusone.

TheaboveversionoftheCookieMonsterproblemhasbeenstreamlinedabittokeepthisproblemsimpleenoughtosolvehere.ThemoregeneralproblemformulationallowsCookieMonsterchooseanysubsetofremainingpiles,andremovethesamefreelychosennumberofcookiesfromeachpileinthechosensubset.Interestedstudentscancheckoutthearticle“OntheCookieMonsterProblem”aboutthesubtlecomplexitiesofthegeneralproblemformulation.

piles Expectedresult

(optimalmoves)

[1, 2, 3, 4, 5, 6] 3 [4, 2, 1]

[2, 3, 5, 8, 13, 21, 34, 55, 89] 5 [55, 21, 8, 3, 2]

[1, 10, 17, 34, 43, 46] 5 [34, 9, 8, 3, 1]

[11, 26, 37, 44, 49, 52, 68, 75, 87, 102]

6 [37, 31, 15, 12, 7, 4]

[2**n for n in range(10)] 10 [512, 256, 128, 64, 32, 16, 8, 4, 2, 1]

Autocorrect for sausage fingers

def autocorrect_word(word, words, df):

In thisdayandageallyouwhippersnappersaresurely familiarwithautocorrect that replacesanon-word with the “closest" real word in the dictionary. Many techniques exist to guess moreaccuratelywhattheuserintendedtowrite.Manyoldpeoplesuchasyourinstructor,alreadybaf0ledby technological doodads and thingamabobs in all your Tikkity Tok videos, often inadvertentlypressavirtualkeysomewhereneartheintendedkey.Forexample,whenthenon-existentwordis'cst',theintendedwordseemsmorelikelytohavebeen'cat' than'cut',assumingthatthetextwasenteredusingtheordinaryQWERTYkeyboardwherethecharactersaandsareadjacent.

Givenaword,alistofwords,andadistancefunctiondfthattellshow“far”the0irstkeyisfromthesecond(forexample,df('a','s')==1anddf('a','a')==0),returnthewordinthelistofwordsthathavethesamenumberoflettersthatminimizesthetotaldistance,measuredasthesumof thedistancesbetween thekeys in samepositions If severalwordsareequidistant fromword,returnthe0irstofthesewordsinthedictionaryorder.

More advanced autocorrect techniques use the surrounding context to suggest the bestreplacement,seeingthatnotallwordsareequallylikelytobetheintendedword,giventherestofthesentence.Forexample,themisspelling'urc'shouldprobablybecorrectedverydifferentlyinthesentence“Thegatewaywasanurcmadeofgraniteblocks”thaninthesentence“Thebravelittlehobbitswunghisswordatthesmellyurc.”Similarly,eventhough'lobe'isaperfectlyvalidwordby itself, “I lobeyou!” ismost likely a typo; andwhoeverwrote just oneword'hellonthere'probablymeanttowritetwobutmissedthespacebaratthebottomrow…oritcouldevenbethreewords,assumingthatthespacebardetectionwassomehowbroken.

word Expectedresult

'qrc' 'arc'

'jqmbo' 'jambo'

'hello' 'hello'

'interokay' 'interplay'

Uambcsrlne the wrod

def unscramble(words, word):

SmdboeoynteoicdafewyreasagotahtthelretetsisndieEisgnlhwdorscanberonmaldyslmecbradwouhtitantifecfgtiehrrlaibdiateytoomcuh,piovreddthatyoukeepthefrsitandthelastltetersastehywere.Gevina lsitofwords gtuaraenedtobesoterd,andoneserlcmbadwrod, tihs fctouninshulodrterunthe listofwrdostahtcloudhvaebeentheorgiianlwordtahtgotseambclrd,andofcsorueretruntahtlsitwtihitswdrosinapcabihaetlloerdrtoenrsuetheuaigntbmuiyofatematoudtesting.Inthevastmaitjoryofceass,thislistwlilcatnoinonlyonewrod.

Writingthe0iltertotransformthegivenplaintexttotheabovescrambledformisalsoagoodlittleprogrammingexerciseinPython.Thisleadsustoausefulestimationexercise:howlongwouldtheplaintext have to be for you towrite such a 0ilter yourself instead of scrambling theplaintext byhandasyouwould ifyouneededtoscramble justoneword? Ingeneral,howmanytimesdoyouthinkyouneedtosolvesomeparticularproblemuntilitbecomesmoreef0icienttodesign,writeanddebugaPythonscripttodoit?Wouldyouranswerchangeif it turnedoutthatmillionsofpeoplearoundtheworldalsohavethatsameproblem,silentlyscreamingfortheirStrongMansaviourtorideinonhismightyhorsetoautomatethisrepetitiveanderror-pronetask?CouldtheveryreaderofthissentenceperhapsbeTheOnewhotheancientprophecieshavemerelyhintedat,comingtosolveallourcomputationalproblems?

wrod Etecxepdrssuelt(unsigthewroslditwdors_sroted.txt)

'tartnaas' ['tantaras', 'tarantas', 'tartanas']

'aierotsd' ['asteroid']

'ksmrseah' ['kersmash']

'bttilele' ['belittle', 'billette']

Substitution words

def substitution_words(pattern, words):

Given a list ofwords (once again, guaranteed to be in sorted order and each consist of the 26lowercaseEnglishlettersonly)andapattern thatconsistsofuppercaseEnglishcharacters,thisfunction should returna listofprecisely thosewords thatmatch thepattern in the sense thatthereexistsasubstitutionfromuppercaseletterstolowercaselettersthatturnsthepatternintothe word. Tomake this problem interesting, this substitutionmust be injective, so that no twodifferentuppercaselettersinthepatternmaptothesamelowercaseletter.

Forexample,theword'akin'matchesthepattern'ABCD'withthesubstitutionsA→a,B→k,C→iand D→n. However, the word 'area' would not match that same pattern, since both patterncharactersAandDwouldhavetobenon-injectivelymappedtothesamelettera.

pattern Expectedresult(usingthewordlistwords_sorted.txt)

'ABBA' ['abba', 'acca', 'adda', 'affa', 'akka', 'amma', 'anna', 'atta', 'boob', 'deed', 'ecce', 'elle', 'esse', 'goog', 'immi', 'keek', 'kook', 'maam', 'noon', 'otto', 'peep', 'poop', 'sees', 'teet', 'toot']

'ABABA' ['ajaja', 'alala', 'anana', 'arara', 'ululu']

'CEECEE' ['beebee', 'booboo', 'muumuu', 'seesee', 'soosoo', 'teetee', 'weewee', 'zoozoo']

'ABCDCBA' ['adinida', 'deified', 'hagigah', 'murdrum', 'reifier', 'repaper', 'reviver', 'rotator', 'senones']

'DEFDEF' 76words,0irstthreeofwhichare['akeake', 'atlatl', 'barbar']

'ABCDEFGIJKLM' 243words,0irstthreeofwhichare['absorptively', 'adjunctively', 'adsorptively']

Manhattan skyline

def manhattan_skyline(towers):

This classic problem in computational geometry (essentially, geometry using only integerarithmeticwithoutanyofthosenastytranscendentalfunctions;yes,notonlyisthatanactualplace,butIhavecomeheretoleadmypeopleintothatpromisedland)isbestillustratedbypicturesandanimationssuchasthoseonthepage"TheSkylineproblem".Givenalistofrectangulartowersastuples(s,e,h) wheres ande arethestartandendx-coordinateswithe>s sothattenementisnot 0it only for immigrants fresh off the Flatland plane (surelyRodgers andHammersteinwouldhave turned thisbackstory intoadelightfulditty) andh is theheightof that tower, compute thetotalvisibleareaofthetowers.Becarefulnottodoublecount theareaofpartiallyoverlappingtowers.Alltowerssharethesame0latgroundbaseline.

Theclassicsolution illustrates the importantsweep linetechniquethatstartsbycreatinga listofprecisely thosex-coordinate valueswhere something relevant to theproblem takesplace. In thisproblem, therelevantx-coordinatesare thosewheresometowereitherstartsorends.Next, loopthroughthesetowersinascendingorder,updatingyourcomputationfortheintervalbetweenthecurrentrelevantx-coordinateandthepreviousone.Inthisparticularproblem,youneedtomaintainalistofactivetowerssothattower(s,e,h) becomesactivewhenx==s,andbecomesinactiveagainwhenx==e.Insideeachinterval,onlythetallestactivetowerisaddedtheareasummation.

The automated tester script will produce start and end coordinates from an exponentiallyincreasingscale.Thisputskiboshonsolvingthisproblemwiththeinferiormethodthatbuildsupthelistofallpositionsfromzerouptothemaximumendcoordinateintowers,loopsthroughthetowerstoupdatethetallesttowerheightateachpositionwithaninnerloop,and0inallysumsupthesepositionheightstripsforthetotalarea.

towers Expectedresult

[(0, 5, 2), (1, 3, 4)] 14

[(3, 4, 1), (1, 6, 3), (2, 5, 2)] 15

[(-10, 10, 4), (-8, -6, 10), (1, 4, 5)] 95

[(s, 1000-s, s) for s in range(500)] 249500

[(s, s+(s*(s-2))%61+1, max(1,s*(s%42))) for s in range(100000)]

202121725069

Count overlapping disks

def count_overlapping_disks(disks):

Right on the heels of the previousManhattan skyline problem, here is another classic of similarspirit to be solved ef0iciently with a sweep line algorithm. Given a list of disks on the two-dimensionalplanerepresentedastuples(x,y,r)sothat(x,y)isthecenterpointandristheradiusof thatdisk,counthowmanypairsofdisks intersectsothattheirareashaveat leastonepointincommon.Twodisks(x1,y1,r1)and(x2,y2,r2)intersectifandonlyiftheysatisfythePythagorean inequality (x2-x1)**2+(y2-y1)**2<=(r1+r2)**2. Note again how thispreciseformularunsonpureintegerarithmeticwheneveritsargumentsareintegers,sonosquarerootsor anyother irrationalnumbers gumup theworkswith theirdecimalnoise. (This formulaalsousestheoperator<=insteadof<tocounttwokissingdisksasanintersectingpair.)

Forthisproblem,crudelyloopingthroughallpossiblepairsofdiskswouldwork,butalsobecomehorrendouslyinef0icientforlargerlists.However,asweeplinealgorithmcansolvethisproblemnotjusteffectivelybutalsoef<iciently(acrucialbutoftenoverlooked“eff-ing”distinction)bylookingat a far fewerpairs of disks.Again, sweep through the space from left to right for all relevantx-coordinate values and maintain the set of active disks at the moment. Each individual disk(x,y,r) enters the active set when the vertical sweep line reaches the x-coordinatex-r, andleavestheactivesetwhenthesweeplinereachesx+r.Whenadiskenterstheactiveset,youneedtolookforitsintersectionsonlyinthisactiveset.

disks Expectedresult

[(0, 0, 3), (6, 0, 3), (6, 6, 3), (0, 6, 3)] 4

[(4, -1, 3), (-3, 3, 2), (-3, 4, 2), (3, 1, 4)] 2

[(-10, 6, 2), (6, -4, 5), (6, 3, 5), (-9, -8, 1), (1, -5, 3)]

2

[(x, x, x//2) for x in range(2, 101)] 2563

Ordinary cardinals

def sort_by_digit_count(items):

Sortingcanbeperformedmeaningfullyaccordingtoarbitrarycomparisoncriteria,aslongasthosecriteriasatisfythemathematicalrequirementsofatotalorderingrelation.Toplayaroundwiththisconcept togrok it, letusde0ineawackyorderingrelationofpositive integerssothat foranytwointegers, theonethatcontainsthedigit9moretimes isconsideredtobe larger,regardlessof themagnitudeandotherdigitsofthesenumbers.Forexample,99>12345678987654321>10100000inthis ordering. If both integers contain the digit 9 the same number of times, the comparisonproceedstothenextlowerdigit8,andsoondownthereuntilthe0irstdistinguishingdigithasbeendiscovered.Ifbothintegerscontaineverydigitfrom9to0pairwisethesamenumberoftimes,theordinaryintegerordercomparisondeterminestheirmutualordering.

As explained in your friendly local discrete math course, the above relation is transitive andantisymmetric,andthereforeanorderingrelationforintegers.OutsideitsabsurdistentertainmentvalueitisuselessinTheRealWorld,though.Theordinaryorderingofordinalsthatwetendtograntthe statusofbeingalmost somesortof lawofnature isusefulbecause itplaysalongnicelywithusefularithmeticoperationssuchasaddition(forexample,a+c<b+cwhenevera<b)tomaketheseoperationsmorepowerfulinthissymbioticrelationship.

items Expectedresult

[9876, 19, 4321, 99, 73, 241, 111111, 563, 33]

[111111, 33, 241, 4321, 563, 73, 19, 9876, 99]

[111, 19, 919, 1199, 911, 999] [111, 19, 911, 919, 1199, 999]

[1234, 4321, 3214, 2413] [1234, 2413, 3214, 4321]

list(range(100000)) (alistof100,000elementswhose0irst0iveelementsare[0, 1, 10, 100, 1000]andthelast0iveare[98999, 99899, 99989, 99998, 99999])

Count divisibles in range

def count_divisibles_in_range(start, end, n):

Letustakeabreatherbytacklingaproblemsimpleenoughthatitssolutionneedsonlyacoupleofconditional statements and some arithmetic, but not even one loop or anythingmore fancy. Thedif0iculty iscomingupwiththeconditionsthatcoverallpossiblecasesof thisproblemjustright,includingallofthepotentiallytricksyedgeandcornercases,withoutbeingoff-by-oneanywhere.Giventhreeintegersstart,end andn sothatstart<=end,counthowmanyintegersbetweenstart andend, inclusive, are divisible byn. Sure, the distinguished gentleman could solve thisproblemasaone-linerwiththelistcomprehension

return len([x for x in range(start, end+1) if x%n == 0])

butofcoursetheauthor'sthumbtacticallyrestingonthescaleoftheautomatedtesterensuresthatanybodytryingtosolvethisproblemwithsuchablunttoolwill0indthemselvesrunningoutofbothtime and space! Your code should have no loops at all, but use only integer arithmetic andconditionalstatementstorootoutthetruth.Also,becarefulwithvariousedgecasesandoff-by-oneticks lurking inthebushes.Notethateitherstart orend canwellbenegativeorzero,butn isguaranteedtobegreaterthanzero.

start end n Expectedresult

7 28 4 6

-77 19 10 9

-19 -13 10 0

1 10**12 - 1 5 199999999999

0 10**12 - 1 5 200000000000

0 10**12 5 200000000001

-10**12 10**12 12345 162008911

Bridge hand shape

def bridge_hand_shape(hand):

Inthecardgameofbridge,eachplayerreceivesahandofexactlythirteencards.Theshapeofthehand is the distribution of these cards into the four suits in the exact order of spades, hearts,diamonds,andclubs.Givenabridgehandencodedasintheexamplescriptcardproblems.py,return the list of these four numbers. For example, given a hand that contains 0ive spades, nohearts,0ivediamondsandthreeclubs,thisfunctionshouldreturn[5, 0, 5, 3].Notethatthecardsinhand canbegiventoyourfunctioninanyorder,sinceinthisquestiontheplayerhasnotyetmanuallysortedhishand.Youranswerstillmust listall foursuits in theircanonicalorder,sothatotherplayerswillalsoknowwhatyouaretalkingabout.

hand Expectedresult

[('eight', 'spades'), ('king', 'diamonds'), ('ten', 'diamonds'), ('three', 'diamonds'), ('seven', 'spades'), ('five', 'diamonds'), ('two', 'hearts'), ('king', 'spades'), ('jack', 'spades'), ('ten', 'clubs'), ('ace', 'clubs'), ('six', 'diamonds'), ('three', 'hearts')]

[4, 2, 5, 2]

[('ace', 'spades'), ('six', 'hearts'), ('nine', 'spades'), ('nine', 'diamonds'), ('ace', 'diamonds'), ('three', 'diamonds'), ('five', 'spades'), ('four', 'hearts'), ('three', 'spades'), ('seven', 'diamonds'), ('jack', 'diamonds'), ('queen', 'spades'), ('king', 'diamonds')]

[5, 2, 6, 0]

Milton Work point count

def milton_work_point_count(hand, trump='notrump'):

Playing cards are represented as tuples(rank,suit) as in ourcardproblems.py exampleprogram.The trick takingpowerofabridge hand isestimatedwithMiltonWorkpoint count,ofwhichwe shall implement a version that is simple enough for beginners of either Pythonor thegameofbridge!Lookingat abridgehand that consistsof thirteencards, 0irst give it4points foreachace,3pointsforeachking,2pointsforeachqueen,and1pointforeachjack.Thatshouldbesimpleenough.Thisrawpointcountisthenadjustedwiththefollowingrules:

● If the hand contains one four-card suit and three three-card suits, subtract one point forbeing<lat.(Flathandsrarelyplayaswellasnon-0lathandswiththesamepointcount.)

● Add1pointforeverysuitthathas0ivecards,2pointsforeverysuitthathassixcards,and3pointsforeverysuitwithsevencardsorlonger.(Shapeispowerinoffence.)

● Ifthetrump suitisanythingotherthan'notrump',add5pointsforeveryvoid(thatis,suitwithoutanycardsinit)and3pointsforeverysingleton(thatis,asuitwithexactlyonecard)foranyothersuitthanthetrumpsuit.(Voidsandsingletonsaregreatwhenyouareplayingasuitcontract,butverybadinanotrumpcontract.Beingvoidinthetrumpsuitis,ofcourse,extremelybad!)

hand(eachhandbelowhasbeensortedbysuitsforreadability,butthetestercanandwillgivethesecardstoyourfunctioninanyorder)

trump Expectedresult

[('four', 'spades'), ('five', 'spades'), ('ten', 'hearts'), ('six', 'hearts'), ('queen', 'hearts'), ('jack', 'hearts'), ('four', 'hearts'), ('two', 'hearts'), ('three', 'diamonds'), ('seven', 'diamonds'), ('four', 'diamonds'), ('two', 'diamonds'), ('four', 'clubs')]

'diamonds' 8

[('three', 'spades'), ('queen', 'hearts'), ('jack', 'hearts'), ('eight', 'hearts'), ('six', 'diamonds'), ('nine', 'diamonds'), ('jack', 'diamonds'), ('ace', 'diamonds'), ('nine', 'clubs'), ('king', 'clubs'), ('jack', 'clubs'), ('five', 'clubs'), ('ace', 'clubs')]

'clubs' 20

[('three', 'spades'), ('seven', 'spades'), ('two', 'spades'), ('three', 'hearts'), ('queen', 'hearts'), ('nine', 'hearts'), ('ten', 'diamonds'), ('six', 'diamonds'), ('queen', 'diamonds'), ('ace', 'diamonds'), ('nine', 'clubs'), ('four', 'clubs'), ('five', 'clubs')]

'notrump' 7

Never the twain shall meet

def hitting_integer_powers(a, b, tolerance=100):

Powersofintegersrapidlyblowupandbecometoolargetobeusefulinourdailylives.Outsidetimeand space, all alonewithnohumanminds towatchover their journey that isparadoxicallybothin0inite and instantaneous, these sequences probe through the space of positive integers withexponentially increasing gaps that eventually contain entire universes and all their possibletimelinesencodedinsidethem.Fortunately,Pythonallowsustoplayaroundwithintegerpowersofmillions of digits. Its mechanical decisions will reliably and unerringly dissect these slumberingEldritchabominationsthatourmortalmindscouldnotbegintovisualize,evenasourlogicticklestheirbelliesinawaythathopefullyfeelssuf0icientlypleasantasnottoangerthem.

Exceptwhen theprime factorsofa andb already co-operate, the ironhandof theFundamentalTheoremofArithmeticdictatesthattheintegerpowersa**pa andb**pb canneverbeequalforanytwopositiveintegerexponentspaandpb.However,inthejovialspiritof"closeenoughforthegovernment work", we de0ine such powers to “hit” if their difference abs(a**pa-b**pb)multiplied by thetolerance is atmost equal to the smaller of those powers. (This de0initionintentionally avoids division to keep it both fast and accurate for arbitrarily large integers.) Forexample,tolerance=100expectsa**paandb**pbtobewithin1%.Forgivenpositiveintegersaandb,returnthesmallestintegerexponents(pa,pb)thatsatisfythetolerancerequirement.

This problemwas inspired by the Riddler Express problem of the column "Can you get anotherhaircutalready?"ofTheRiddler,anexcellentsourceofpuzzlesofthisgeneralspirit.

a b tolerance Expectedresult

9 10 5 (1, 1)

2 4 100 (2, 1)

2 7 100 (73, 26)

3 6 100 (137, 84)

4 5 1000 (916, 789)

10 11 1000 (1107, 1063)

42 99 100000 (33896, 27571)

Bridge hand shorthand form

def bridge_hand_shorthand(hand):

Inliteratureonthegameofcontractbridge,handsareoftengiveninabbreviatedformthatmakestheirrelevantaspectseasiertovisualizeataglance. Inthisabbreviatedshorthandform,suitsarealwayslistedintheexactorderofspades,hearts,diamondsandclubs,sonospecialsymbolsareneededtoshowwhichsuit iswhich.Theranks ineachsuitare listedas letters from'AKQJ' foraces and faces, and all spot cards lower than jack are written out as the same letter 'x' toindicatethatitsexactspotvalueisirrelevantfortheplaymechanicsofthathand.Theselettersmustbe listed in descending order of ranksAKQJx. If some suit isvoid, that is, the hand contains nocardsofthatsuit,thatsuitisabbreviatedwithaminussigncharacter'-'.Theshorthandformsfortheindividualsuitsareseparatedusingsinglespaces,withnotrailingwhitespace.

(Thenagain,theauthordidonceseeaproblemwhereafreakingeightwasarelevantrank...)

hand(eachhandbelowissortedbysuitsforreadability,butyourfunctioncanreceivethese13cardsfromthetesterinanyorder)

Expectedresult

[('four', 'spades'), ('five', 'spades'), ('ten', 'hearts'), ('six', 'hearts'), ('queen', 'hearts'), ('jack', 'hearts'), ('four', 'hearts'), ('two', 'hearts'), ('three', 'diamonds'), ('seven', 'diamonds'), ('four', 'diamonds'), ('two', 'diamonds'), ('four', 'clubs')]

'xx QJxxxx xxxx x'

[('three', 'spades'), ('queen', 'hearts'), ('jack', 'hearts'), ('eight', 'hearts'), ('six', 'diamonds'), ('nine', 'diamonds'), ('jack', 'diamonds'), ('ace', 'diamonds'), ('nine', 'clubs'), ('king', 'clubs'), ('jack', 'clubs'), ('five', 'clubs'), ('ace', 'clubs')]

'x QJx AJxx AKJxx'

[('three', 'spades'), ('seven', 'spades'), ('two', 'spades'), ('three', 'hearts'), ('queen', 'hearts'), ('nine', 'hearts'), ('ten', 'diamonds'), ('six', 'diamonds'), ('queen', 'diamonds'), ('ace', 'diamonds'), ('nine', 'clubs'), ('four', 'clubs'), ('five', 'clubs')]

'xxx Qxx AQxx xxx'

[('ace', 'spades'), ('king', 'spades'), ('queen', 'spades'), ('jack', 'spades'), ('ten', 'spades'), ('nine', 'spades'), ('eight', 'spades'), (seven, 'spades'), ('six', 'spades'), ('five', 'spades'), ('four', 'spades'), ('three', 'spades'), ('two', 'diamonds')]

'AKQJxxxxxxxx - x -'

Points, schmoints

def losing_trick_count(hand):

TheMiltonWork point count in an earlier problem is only the 0irst baby step in estimating theplayingpowerofabridgehand.Oncethepartnershipdiscovers theyhaveagoodtrump0it,handevaluationcontinuesmoreaccuratelyusingsome formof losing trickcount.Forexample,asmallslaminspadeswith'AKxxxxx - Kxxx xx'facing'xxxx xxxxx AQx -'isalockdespitepossessingonly16ofthe40highcardpointsinthedeck,assumingthattheopponentslookingattheirownmassiveshapesletyouplaythatslaminsteadofmakingagreatsacri0icebybiddingsevenoftheirsuit.(Advancedpartnershipsareabletojudgesuchthingstoastonishingprecisionmerelyfromwhathas,andespeciallywhathasnot,beenbid!)Ontheother“hand”(heh),anyslamisdeadinthewaterwiththe'QJxxx xx AKx QJx' facing'AKxxx QJ QJx AKx',thankstothehorrendousduplicationoftheusefulcards.(“Ifitquackslikeaduck…")

Inthisproblem,wecomputethebasiclosingtrickcountasgiveninstep1of"Methodology"sectionoftheWikipediapage"LosingTrickCount"withoutany0inerre0inements.Keepinmindthatnosuitcanhavemorelosersthanithascards,andnevermorethanthreelosersevenifthehandhastencardsofthatsuit!Thefollowingdictionary(composedbystudentShuZhuSuduringtheFall2018semester)mightalso comehandy for the combinationswhose losing trick countdiffers from thestringlength,onceyouconverteachJoftheshorthandformintoanx:

{'-':0,'A':0,'x':1,'Q':1,'K':1,'AK':0,'AQ':1,'Ax':1,'KQ':1,'Kx':1,'Qx':2,'xx':2, 'AKQ':0, 'AKx':1, 'AQx':1,'Axx':2, 'Kxx':2, 'KQx':1, 'Qxx':2, 'xxx':3}

hand Expectedresult

[('ten', 'clubs'), ('two', 'clubs'), ('five', 'clubs'), ('queen', 'hearts'), ('four', 'spades'), ('three', 'spades'), ('ten', 'diamonds'), ('king', 'spades'), ('five', 'diamonds'), ('nine', 'hearts'), ('ace', 'spades'), ('queen', 'spades'), ('six', 'spades')]

7

[('eight', 'hearts'), ('queen', 'spades'), ('jack', 'hearts'), ('queen', 'hearts'), ('six', 'spades'), ('ten', 'hearts'), ('five', 'clubs'), ('jack', 'spades'), ('five', 'diamonds'), ('queen', 'diamonds'), ('six', 'diamonds'), ('three', 'spades'), ('nine', 'clubs')]

8

Bulls and cows

def bulls_and_cows(guesses):

Inthetwo-playergameof"BullsandCows",reincarnatedaftertheseventiesRuralPurgeunderthemoredramaticandurbantitle"Mastermind" incolourfulplastic, the0irstplayerthinksupa four-digitsecretnumberwithalldigitsdifferent,suchas8723or9425.(Forsimplicity,thedigitzeroisnotusedinourversionofthisproblem.)Thesecondplayertriestopinpointthissecretnumberbyrepeatedlyguessingsomefour-digitnumbers.Aftereachguess, the0irstplayerrevealshowmanybulls,therightdigitintherightposition,andcows,therightdigitbutinthewrongposition,thatparticularguesscontains.Forexample, ifthesecretnumberis1729,theguess5791containsonebull(thedigit7)andtwocows(thedigits9and1).Theguess4385,ontheotherhand,containsnobullsorcows...thusneatlypruningallfourdigitsfromfutureguesses!

Thisfunctionshouldlistallnumbersthatstillcouldbethesecretnumberaccordingtotheresultsofthelistofguesses completedsofar.Eachguessisgivenasatuple(guess, bulls, cows).This functionshouldreturnthe listofsuchconsistent four-digit integers inascendingorder.Notethat it is verymuch possible for this result list to be empty, if the results of theguesses areinherentlycontradictory. (Good functionsought toberobust so that theydo theright thingevenwhengivensyntacticallycorrectbutsemanticallymeaninglessargumentvalues.)

Start by creating a list of all four-digit numbers that do not contain any repeated digits. Loopthrough the individualguesses, and for each guess, use a list comprehension to create a list ofnumbersthatwereinthepreviouslistandarestillconsistentwiththecurrentguess.Afteryouhavedone all that, oi jolly well then mate, “When you have eliminated all which is impossible, thenwhateverremains,howeverimprobable,mustbethetruth.”—SherlockHolmes

Thisproblemanditsmyriadgeneralizationstoanexponentiallylargernumberofpossibilities(forexample,otherwisethesamegamebutplayedwithEnglishwords)canbesolvedinmorecleverandef0icientways than the abovebrute force enumeration.However,we shall let that one remain atopicforalatercourseonadvancedalgorithms.

guesses Expectedresult

[(1234, 2, 2)] [1243, 1324, 1432, 2134, 3214, 4231]

[(8765, 1, 0), (1234, 2, 1)] [1245, 1263, 1364, 1435, 1724, 1732, 2734, 3264, 4235, 8134, 8214, 8231]

[(1234, 2, 2), (4321, 1, 3)] []

[(3127, 0, 1), (5723, 1, 0), (7361, 0, 2), (1236, 1, 0)]

[4786, 4796, 8746, 8796, 9746, 9786]

Frequency sort

def frequency_sort(items):

Sort the given list of integer items so that its elements end up in the order of decreasingfrequency,thatis,thenumberoftimesthattheyappearinitems.Iftwoelementsoccurwiththesamefrequency,theyshouldendupintheascendingorderoftheirelementvalueswithrespecttoeachother,asisthestandardpracticeinsortingthings.

Thebestwaytosolvethisproblemisto“LetGeorgedoit”,orwhicheverwayyouwishtoputthisconceptofpassing thebucktoahaplessunderling,byassigning theroleofGeorge to thePythonsortfunction.Wearegoingtotellthesortfunctiontoperformthissortingaccordingtoacustomsortingcriterion,aswasdoneinthelectureexamplescriptcountries.py.

Startbycreatingadictionarytokeeptrackofhowmanytimeseachelementoccursinsidethearray.Then,use these counts stored in thatdictionaryas thesortingkey of theactual arrayelements,breakingtiesonthefrequencybyusingtheactualelementvalue.(Ifyoualsothenrememberthatthe order comparison between Python tuples is lexicographic, you don't even have to burdenyourselfwiththeworkneededtobreakthesetiesbetweentwoequallyfrequentvalues...)

items Expectedresult

[4, 6, 2, 2, 6, 4, 4, 4] [4, 4, 4, 4, 2, 2, 6, 6]

[4, 6, 1, 2, 2, 1, 1, 6, 1, 1, 6, 4, 4, 1]

[1, 1, 1, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2]

[17, 99, 42] [17, 42, 99]

['bob','bob','carl','alex','bob'] ['bob','bob','bob','alex','carl']

Calling all units, B-and-E in progress

def is_perfect_power(n):

A positive integern is a perfect power if it can be expressed as the powerb**e for some twointegersbandethatarebothgreaterthanone.(Anypositiveintegerncanalwaysbeexpressedasthetrivialpowern**1,sowedon'tcareaboutthose.)Forexample,theintegers32,125and441areperfectpowerssincetheyequal2**5,5**3and21**2,respectively.

This function should determinewhether the positive integern is a perfect power. Your functionneeds to somehow iterate througha suf0icientnumberofpossible combinationsofb ande thatcouldwork,returningTruerightawaywhenyou0indsomebandethatsatisfyb**e == n,andreturningFalse whenall relevantpossibilities forb ande havebeen triedand foundwanting.Sincen cangetprettylarge,yourfunctionshouldnotexaminetoomanycombinationsofb andeabove andbeyond those that arebothnecessary and suf0icient to reliablydetermine the answer.Achievingthisef0iciencyisthecentraleducationalpointofthisproblem.

A tester for this problem canbebuilt onCatalan’s conjecture, thesedays a provenmathematicaltheorem that says that after the special case of the two consecutive perfect powers 8 and 9,wheneverthepositiveintegernisaperfectpower,n-1canneverbeaperfectpower.Thistheoremmakes it easy to generate pseudorandom test cases with known answers, both positive andnegative.Forexample,wedon'thavetoslogthroughallpotentialwaystoexpressthenumberasanintegerpower toknow from theget-go that12345**67890-1 isnotaperfectpower.Thisalsoillustratesthecommonasymmetrybetweenperformingacomputationtooppositedirections.Givensomechunky integersuchas4922235242952026704037113243122008064,butnot the formulathatoriginallyproducedit,itisnotthateasytotellwhetherthatnumberisaperfectpower,orsomeperfectpowerplusminusone.

n Expectedresult

42 False

441 True

469097433 True

12**34 True

12**34 - 1 False

Lunatic multiplication

def lunar_multiply(a, b):

This problem was inspired by another jovial Numberphile video "Primes on the Moon'' by NeilSloane(asin)thatyoushouldwatch0irsttogetanideaofhowthiswacky“lunararithmetic”works.Formerly known as “dismal arithmetic”, addition and multiplication of natural numbers arerede0inedsothataddingtwodigitsmeanstakingtheirmaximum,whereasmultiplyingtwodigitsismeanstakingtheirminimum.Forexample,2+7=7+2=7and2*7=7*2=2.Unlikeordinaryaddition, therecanneverbeacarry to thenextcolumnofdigits,nomatterhowmany individualdigits are added together in that column. For numbers with several digits, addition andmultiplication work exactly as you learned back in grade school, except that the shifted digitcolumnsfromlunarmultiplicationoftheindividualdigitsareaddedinthesamelunaticfashion.

Thesewacky operators de0ine an algebraic ringwhere useful and important algebraic identitiessuchasab=ba, (a+b)+c=a+(b+c)anda(b+c)=ab+achold,alongwitheverythingthatisentailedbythoseidentities.Theunitelementforadditioniszero,sameasinordinaryarithmetic.However, if only to rouse theboomers in the audience, theunit formultiplication is not onebuttheir beloved number nine, since 9n =n for any natural numbern, as you can easily verify. Thisfunctionshouldcomputeandreturnthelunarproductoftwointegersaandb.

a b Expectedresult

2 3 2

8 9 8

11 11 111

17 24 124

123 321 12321

357 64 3564

123456789 987654321 12345678987654321

Distribution of abstract bridge hand shapes

def hand_shape_distribution(hands):

Thisisacontinuationoftheearlierproblemtocomputetheshapeofthegivenbridgehand.Inthatproblem,theshapes[6, 3, 2, 2]and[2, 3, 6, 2]wereconsidereddifferent,astheyverymuch would be in the actual bidding and play of the hand. However, in this combinatorialgeneralized version of this problem,we shall consider twohand shapes like these two to be thesameabstractshapeiftheyareequalwhenweonlylookatthesortedcountsofthesuits,butdon'tcareabouttheorderofwhichparticularsuitstheyhappentobe.

Givenalistofbridgehands,eachhandgivenasalistof13cardsencodedthesamewayasinallofthepreviouscardproblems,createandreturnaPythondictionarythatcontainsallabstractshapesthat occur within hands, each shape mapped to its count of occurrences in hands. Note thatPythondictionary keys cannot be lists (Python lists aremutable, and changing the contents of adictionarykeywouldbreak the internalorderingof thedictionary) soyouneed to represent theabstracthandshapesasimmutabletuplesthatcanbeusedaskeysinsideyourdictionary.

As tabulated on "Suit distributions" in "Durango Bill's Bridge Probabilities and Combinatorics",there exist precisely39possible abstract shapesof thirteen cards, themost commonofwhich is4-4-3-2, followed by the shape 5-3-3-2. Contrary to intuition, the most balanced possible handshape4-3-3-3turnsouttobesurprisinglyunlikely,trailingbehindfarlessbalancedshapes5-4-3-1and 5-4-2-2 that onemight have assumed to be less frequent. (Understandingwhy randomnesstends to produce variance rather than converging to complete uniformity is a great aid inunderstanding many other counterintuitive truths about the behaviour of random processes incomputerscienceandmathematics.)

For example, if itwere somehowpossible to give to your function the list of all 635,013,559,600possible bridge hands and not run out of the heap memory in the Python virtual machine, thereturned dictionarywould contain 39 entries for the 39 possible hand shapes, two examples oftheseentriesbeing(4,3,3,3):66905856160 and(6,5,1,1):4478821776.Ourautomatedtester will try out your function with amuch smaller list of pseudo-randomly generated bridgehands,butatleastforthecommonhandtypesthatyoumightexpecttoseeeverydayatthedailyduplicateofthelocalbridgeclub,thepercentageproportionsreallyoughtnotbethatdifferentfromtheexactanswersifmeasuredoverasuf0icientlylargenumberofrandomhands.

Fibonacci sum

def fibonacci_sum(n):

Fibonaccinumbersareacliche in introductorycomputerscience,especially inteachingrecursionwherethisfamouscombinatorialseriesismainlyusedtoreinforcethebeliefthatrecursionissilly.However,allclichesbecameclichesinthe0irstplacebecausetheyweresojustdarngoodthateveryTom,DickandHarrykeptusing them!Letus therefore traipsearound theZeckendorf's theorem,themoreamazingpropertyof these famousnumbers:everypositive integercanbeexpressedexactlyonewayasasumofdistinctnon-consecutiveFibonaccinumbers.

Thesimplegreedyalgorithmcanbeproventoalwaysproducethedesiredbreakdownofnintoasumofdistinctnon-consecutiveFibonaccinumbers:alwaysappendintothelistthelargestpossibleFibonaccinumberfthatisatmostequalton.Thenconverttherestofthenumbern-finthissamemanner,untilnothingremainstobeconverted.Tomaketheresultsuniqueforautomatedtesting,thislistofFibonaccinumbersthatadduptonmustbereturnedindescendingsortedorder.

NotehowthisgreedyconstructionguaranteesthatthechosenFibonaccinumbersaredistinctandcannotcontaintwoconsecutiveFibonaccinumbersFiandFi+1.OtherwisetheirsumFi+2wouldalsohave0itinsidenandbeenusedinsteadofFi+1andthuswouldhavepreventedtheuseofFi+1withthesameargumentinvolvingthenexthigherFibonaccinumberFi+3…

n Expectedresult

10 [8, 2]

100 [89, 8, 3]

1234567 [832040, 317811, 75025, 6765, 2584, 233, 89, 13, 5, 2]

10**10 [7778742049, 1836311903, 267914296, 102334155, 9227465, 3524578, 1346269, 514229, 75025, 6765, 2584, 610, 55, 13, 3, 1]

10**100 (alistof137terms,thelargestofwhichstartswithdigits921684571)

Wythoff array

def wythoff_array(n):

Wythoff array (see the Wikipedia article for illustration) is an in0inite two-dimensional grid ofintegersthatisseededwithoneandtwotostartthe0irstrow.Ineachrow,eachelementequalsthesumoftheprevioustwoelements,sothe0irstrowcontainspreciselytheFibonaccinumbers.

The0irstelementofeachlaterrowisthesmallestintegerc thatdoesnotappearanywhereinthepreviousrows.Sinceeveryrowisstrictlyascendingandgrowsexponentiallyfast,youcan0indthisoutbylookingatrelativelyshort0initepre0ixesoftheserows.Todeterminethesecondelementofthatrow,leta andb bethe0irsttwoelementsofthepreviousrow.Ifthedifferencec-a equalstwo, the second element of that row equals b+3, and otherwise that element equals b+5. Thisconstruction guarantees the Wythoff array to be an interspersion of positive integers; everypositive integer will appear exactly once in the entire in0inite grid, with no gaps or duplicatesanywhere! (This result nicely highlights the deeper combinatorial importance of the deceptivelysimpleFibonaccisequenceaspotentialbuildingblocksofintegersandintegersequences.)

Thedif0icultyinthisproblemisdeterminingthe0irsttwoelementsofeachrow,sincetherestoftherowthenbecomestrivialtogenerateasfarasneeded.ThisfunctionshouldreturnthepositionofnintheWythoffarrayasatwo-tuple(row, col),rowsandcolumnsbothstartingfromzero.

n Expectedresult

21 (0, 6)

47 (1, 5)

1042 (8, 8)

424242 (9030, 6)

39088169 (0, 36)

39088170 (14930352, 0)

Rooks with friends

def rooks_with_friends(n, friends, enemies):

Thosedastardlyrookshaveagaingoneonarampageonageneralizedn-by-nchessboard,justlikeintheearlierproblemofcountinghowmanysquareskepttheiroccupantsfrombeingpulverizedintodustundertheselumberingjuggernauts.Eachindividualrookisagainrepresentedasatwo-tuple(row, col) ofthecoordinatesofthesquareitstandson.However,thisversionoftheproblemintroducesapinchofold-fashionedethnicnepotismtothemixsothatsomeoftheserooksareyourfriends (samecolourasyou)while theothersareyourenemies (theoppositecolour fromyou).Trappedinthishellscape,youcanonlyscurryalongandhopetosurviveuntilthedustsettles.

Friendlyrooksprotectthechesssquaresbystandingbetweenthemandanyenemyrooksthatwanttoinvadethosesquares.Anenemyrookcanattackonlythosesquaresinthesameroworcolumnthatdonotenjoytheprotectionofsuchafriendlyrookstandingbetweenthem.Giventheboardsizenandthelistsoffriendsandenemies(thesetwolistsareguaranteeddisjointsothatnorookscanactaseitherfence-sittersorturncoats),counthowmanyemptysquaresontheboardaresafefromtheenemyrooks.

n friends enemies Expectedresult

4 [(2,2), (0,1), (3,1)] [(3,0), (1,2), (2,3)] 2

4 [(3,0), (1,2), (2,3)] [(2,2), (0,1), (3,1)] 2

8 [(3,3), (4,4)] [(3,4), (4,3)] 48

100 [(r, (3*r+5) % 100) for r in range(1, 100, 2)]

[(r, (4*r+32) % 100) for r in range(0, 100, 2)]

3811

Possible words in Hangman

def possible_words(words, pattern):

Givenalistofpossiblewords,andapatternstringthatisguaranteedtocontainonlylowercaseEnglishlettersatozandasteriskcharacters*,createandreturnasortedlistofwordsthatmatchthepatterninthesenseofthefamouspen-and-paperwordguessinggameofHangman.

Eachpatterncanonlymatchwordsoftheexactsamelength.Inthepositionswherethepatterncontains some letter, the word must contain that very same letter. In the positions where thepattern containsanasterisk,thewordcharacterinthatpositioncanbeanyletterexceptoneofthelettersthatoccurinsidethepattern.InanactualgameofHangman,alloccurrencesofsuchaletterwouldhavealreadybeenrevealedintheearlierroundwithletterasthecurrentguess.

Forexample, thewords'bridge' and'smudge' bothmatchthepattern'***dg*'.However,thewords'grudge'and'dredge'wouldnotmatchthatsamepattern,sincethe0irstasteriskmaynotbematchedwitheitherletter'g'or'd'thatalreadyappearsinsidethepattern.

pattern Expectedresult(usingwordlistwords_sorted.txt)

'***dg*' ['abedge', 'aridge', 'bludge', 'bridge', 'cledge', 'cledgy', 'cradge', 'fledge', 'fledgy', 'flidge', 'flodge', 'fridge', 'kludge', 'pledge', 'plodge', 'scodgy', 'skedge', 'sledge', 'slodge', 'sludge', 'sludgy', 'smidge', 'smudge', 'smudgy', 'snudge', 'soudge', 'soudgy', 'squdge', 'squdgy', 'stodge', 'stodgy', 'swedge', 'swidge', 'trudge', 'unedge']

'*t*t*t*' ['statute']

'a**s**a' ['acystia', 'acushla', 'anosmia']

'*ikk**' ['dikkop', 'likker', 'nikkud', 'tikker', 'tikkun']

All branches lead to Rome

def lattice_paths(x, y, tabu):

Youarestandingat thepoint(x,y) in the latticegridofpairsofnaturalnumbers,andwish tomakeyourwaytotheoriginpoint(0,0).Atanypoint,youareallowedtomoveeitheronestepleftoronestepdown.Furthermore,youareneverallowedtostepintoanyofthepointsinthetabulist.This functionshouldaddupthenumberofdifferentpathsthat leadfromthepoint(x,y) totheorigin(0,0)undertheseconstraints.Thegoal(0,0)isneverpartofthetabulist.

This constrained variation of the classic combinatorial problem turns out to have a reasonablystraightforwardrecursivesolution.Asthebasecase,thenumberofpathsfromtheorigin(0,0)toitself(0,0) equalsone for theemptypath. (Note thecrucialdifferencebetweenanemptypaththatexists,versusanonexistentpath!)Ifthepoint(x,y) isinthetabu list,thenumberofpathsfrom that point (x,y) to the origin equals zero. The same holds for all points whose eithercoordinatex ory isnegative.Otherwise,thenumberofpathsfromthepoint(x,y) totheorigin(0,0)equalsthesumofpathsfromthetwoneighbours(x-1,y)and(x,y-1)fromwhichthecurrentpathcancontinueinamutuallyexclusivefashion.

However, this simple recursion branches into an exponential number of possibilities and wouldtherefore be far too slow for us to execute. Therefore, you should eithermemoize the recursionwithlru_cache,orevenbetter,notuserecursionatallbutbuildupatwo-dimensionallistwhoseentries are the individual subproblem solutions. Fill in the correct valueswith twofor-loops insome order that guarantees that when these loops arrive at position [x][y], the results forpositions[x-1][y]and[x][y-1]neededtocompute[x][y]arealreadythere.

This technique of using for-loops to 0ill out thememoization tables instead of using a recursiveformulaiscalleddynamicprogramming.ThiseleganttechniqueistrulyaskeletonkeythatopensthousandsofdoorsthatHerculeshimselfwouldnotbeabletopryopenwithbruteforce.

x y tabu Expectedresult

3 3 [] 20

3 4 [(2, 2)] 17

10 5 [(6, 1), (2, 3)] 2063

6 8 [(4, 3), (7, 3), (7, 7), (1, 5)] 1932

10 10 [(0, 1)] 92378

100 100 [(0, 1), (1, 0)] 0

Be there or be square

def count_squares(points):

Thisproblemisadaptedfrom"CounttheNumberofSquares"atWolframChallenges,soyoumightwantto0irstcheckoutthatpageforillustrativevisualizationsofthisproblem.

Givenaset ofpoints,eachpointa tuple(x,y) wherex andy arenonnegative integers, thisfunctionshouldcounthowmanysquares exist so thatall fourcornersaremembersofpoints.Note that thesesquaresarenot required tobeaxis-aligned so that their sideswouldhave tobeeitherhorizontalandvertical.Forexample,thepoints(0,3),(3,0),(6,3)and(3,6)de0ineasquare,evenifitmayhappentolooklikealozengefromouraxis-alignedvantagepoint.Aslongasall four sides have the exact same length, be that length an integer or some 0iendishly irrationalnumber,well,thatmakesus“square”atleastinmybook,pardner!

To identify four points that constitute a square, note how every square hasbottom left cornerpoint(x,y) anddirection vector(dx,dy) towards itsupper left corner point that satis0iesdx>=0 anddy>0, sothat thepoints(x+dx,y+dy),(x+dy,y-dx) and(x+dx+dy,y-dx+dy)forthetopleft,bottomrightandtoprightcornersofthatsquare,respectively,arealsoincludedinpoints.Youcanthereforeiteratethroughallpossibilitiesforthebottomleftpoint(x,y)andthedirectionvector(dx,dy) andbeguaranteedto0indallsquaresinthegrid.Butpleasedoatleastmakeanattempttobeeconomicalintheseloops,andmakeyourfunctionsweepupthesesquaresmoreswiftlythanevenTomSwifthimselfevercouldcornerthem.

InterestedstudentscancheckouttheMathologervideo"Whatdoesthisprove?"aboutthisgeneraltopic,ifonlytoseeabeautifulin<initeregressproofofwhysquaresaretheonlyregularpolygonswhosecornerpointscanlieexactlyonthepointsofanintegergrid.

points Expectedresult

[(0,0), (1,0), (2,0), (0,1), (1,1), (2,1), (0,2), (1,2), (2,2)]

6

[(4,3), (1,1), (5,3), (2,3), (3,2), (3,1), (4,2), (2,1), (3,3), (1,2), (5,2)]

3

[(x, y) for x in range(1, 10) for y in range(1, 10)] 540

[(3,4), (1,2), (3,2), (4,5), (4,2), (5,3), (4,1), (5,4), (3, 5), (2,4), (2,2), (1,1), (4,4), (2,5), (1,5), (2,1), (2,3), (4, 3)]

15

Flip of time

def hourglass_flips(glasses, t):

Anhourglass is represented as a tuple(u,l) (the second character is the lowercaseL, not thenumerouno) for the number ofminutes in its upper and lower chambers. Afterm minutes haveelapsed, the state of that hourglasswill be(u-min(u,m),l+min(u,m)). The total amount ofsandinsidethehourglassneverchanges,norwilleitherchambercontainnegativeanti-sand.

Givena listofglasses, your task is to 0indanoptimal sequenceofmoves tomeasureexactlytminutes, scoredas thenumberof individualhourglass 0lipsperformedalong theway.Eachmoveconsistsoftwostages.Youmust0irstwaitforthehourglassthatcurrentlyholdsthelowestnonzeroamount m of sand in its upper chamber to run out. When that happens, choose any subset ofglasses andinstantaneously0lipthischosensubset.Youdon'thaveanychoiceinwaitinginthe0irststage,butinthesecondstageyouenjoyanembarrassmentofrichesof2npossiblemovesfornglasses!Continuesuchtwo-stagemovestobestmeasuretheremainingt-mminutes.

Thisfunctionshouldreturnthesmallestpossiblenumberofindividualhourglass<lipsneededtomeasureexactlyt minutes,orNone ifthisexactmeasurementisimpossible.Thebasecasesofrecursionarewhent equalszeroorwhenexactlyt minutesremaininsomeupperchamber(no0lipsareneeded),orwhent issmallerthanthesmallesttimeremainingintheupperchamberofanyhourglass(nosolutionispossible).Otherwise,updateallhourglassestotheirnewstatesaftermminutes,andloopthroughallpossiblesubsetsofglassesto0lip.Foreachsuchsubset,recursivelyconstruct the optimal sequence ofmoves tomeasure the remainingt-m minutes, and combinethesemovestothebestsolution.

Thegeneratoritertools.product([0,1], repeat=n)yieldsallpossiblen-elementtuplesof[0,1]torepresentthe2npossiblesubsetsofthenindividualglassestobe0lipped.

glasses t Expectedresult

[(7, 0), (11, 0)] 15 2(seehere)

[(4, 0), (6, 0)] 11 None

[(7, 1), (10, 4), (13, 1), (18, 4)] 28 3

[(13, 1), (14, 3)] 22 16

[(10, 1), (13, 4)] 15 None

Bulgarian cycle

def bulgarian_cycle(piles):

Whenthetotalnumberofpebblesinthepilesisthek:thtriangularnumber,iterationoftheearlierBulgariansolitaireproblemisguaranteedtoreachasteadystatewhoseindividualpilesizesaretheintegers1tok,eachexactlyonce.Startedwithsomeothernumberofpebbles,thisiterationwillneverreachsuchasteadystate.Instead,thesystemwilleventuallyre-entersomestatethatithasalreadyvisited,andfromtherekeeprepeatingthesamelimitcycleofstates.Forexample,startingfrom[2, 3, 2],thesystemgoesthroughstates[1, 2, 1, 3],[1, 2, 4],[1, 3, 3],and[2, 2, 3].Sincethislaststate[2, 2, 3]isequalto[2, 3, 2]thatwehavealreadyseenbefore,thiscompletesthelimitcycleoflengthfour.Notethatthecycledoesnotneedtoendatthestartingstate,butitcanendinanyoneofthestateslaterinthissequence.

Thisfunctionshouldcomputethelengthofthelimitcyclestartingfromthegivenpiles.However,note that this limit cycle does not necessarily include the initialpiles, butmay actually beginsomenumberofstatesdowntheroad!TheingenioustortoiseandharealgorithmofRobertFloyddetectsthatiterationhasreturnedtosomepreviouslyseenstate,withouthavingtostoretheentiresequenceof states explicitly inmemory.This algorithmonlyneeds tokeep trackof two separatecurrentstatescalledtortoiseandhare.Bothstartatthesamestateofpiles,andproceedthroughthesamesequenceofstates.However,theharetakestwostepsforeverysteptakenbythetortoise.

Akintotwolongdistancerunnersracingtowardsastadiumsomeunknowndistanceahead,eventhe tortoise will eventually reach the stadium. Running around the stadium track, it will beinevitablyovertakenbythehare,andthepositionwherethesetwoanimalsmeetmustbepartofthelimitcycle.Then,justhavetheharecountitsstepsaroundthestadiumonemoretimewhilethetortoisetakesanaptomarkthespot,sothatthehareknowswhentostopcounting.

piles Expectedresult

[1, 3, 2] 1

[2, 3, 2] 4

[4, 4, 3, 3, 2, 1] 6

[17, 99, 42] 18

[n*n for n in range(1, 51)] 293

Square it out amongst yourselves

def cut_into_squares(a, b):

Rectanglesaregivenastuples(a,b)oftheirwidthandheight,bothpositiveintegers.Arectanglecanbecutintotwosmallerrectangleswitheitherastraighthorizontalorastraightverticalcutatanyintegerposition.Forexample,oneofthepossiblewaystocuttherectangle(5,8)intwopieceswouldbetocut it into(2,8) and(3,8).Anotherwaywouldbetocut it intotwopieces is into(5,4)and(5,4).Andmanyothers,toomanytolisthere.Theresultingsmallerpiecescanthenbefurthercutintosmallerpieces,aslongasthelengthofthesidebeingcutisatleasttwotoallowacut. (Also, at the risk of disappointing the fans of Edward de Bono, you are not allowed to cutmultiplepiecesinonemotionofthebladebystackingpiecesontopofeachother.)

Your task is to keep cutting the given rectangle(a,b) into smaller pieces until each piece is asquare, that is, thewidth of each piece equals its ownheight. This is always possible, since youcouldjustkeepcuttinguntileachpiecehasbecome1-by-1.However,thisfunctionshouldreturnthesmallestnumberofcutsthatachievesthisgoalofmakingeachpieceasquare.

Thisproblemisbestsolvedwithrecursion.Itsbasecasesarewhena==bforapiecethatisalreadyasquaresoyoureturn0,andwhenmin(a,b)==1 allowingno furthercutson theshorterside,returnmax(a,b)-1.Otherwise,loopthroughthepossiblewaystocutthispieceintotwosmallerpieces,recursivelycomputingthebestpossiblewaytocutupthesetwopieces.Returnthenumberofcutsproducedbytheoptimalwayofcuttingthispiece.Sincethisbranchingrecursionwouldvisitits subproblems exponentiallymany times, youwill surelywant to sprinkle some@lru_cachememoizationmagiconittodowngradethatexponentialtangleintoamerequadraticone.

a b Expectedresult

4 4 0

4 2 1

7 6 4

91 31 10

149 139 19

Sum of distinct cubes

def sum_of_distinct_cubes(n):

Positiveintegerscanbebrokendownintosumsofdistinctcubesofpositiveintegers,sometimesinmultipledifferentways.This functionshould 0indandreturnthe listofdistinctcubeswhosesumequalsthegivenpositiveintegern.Shouldnallowseveralbreakdownsintosumsofdistinctcubes,this function must return the lexicographically highest solution that starts with the largestpossible0irstnumbera followedbythelexicographicallyhighestrepresentationoftherestofthenumbern-a*a*a.Forexample,calledwithn=1729,thisfunctionshouldreturn[12, 1]insteadof[10, 9].Ifitisimpossibletoexpressnasasumofdistinctcubes,returnNone.

Unlike in theearlier,muchsimplerquestionofexpressingn asasumofexactly twosquares, theresultcannowcontainanynumberofdistinctterms.Thisproblem, likealmostallsuchproblemsthatcauseanexponentialblowupof two-way“take itor leave it”decisions, isusuallybestsolvedwithrecursionthatexaminesbothbranchesofeachsuchdecisionandreturnstheonethatleadstoabetteroutcome.Thebasecaseiswhenn equalszero.Otherwise,loopdownthepossiblevaluesthatcouldserveasthe0irstelementaintheresult.Foreachsucha,breakdowntherestn-a*a*arecursively into a sum of distinct cubes using only integers smaller than a. Again, to let yourfunctionef0icientlygleamthesecubesevenforlargen,itmightbeagoodideatopreparesomethingthatallowsyoutoquickly0indthelargestintegerwhosecubeisnotlargerthann.

This problem is intentionally restricted to positive integers to keep the number of possibilities0inite.Sincethecubeofanegativenumberisalsonegative,no0initeupperboundforsearchwouldexist if negative numberswere allowed. Breaking some small and simple number into a sum ofexactlythreecubescansuddenlyblowuptobecomeahighlynontrivialproblem...

n Expectedresult

8 [2]

11 None

855 [9, 5, 1]

sum([n*n*n for n in range(11)] [14, 6, 4, 1]

sum([n*n*n for n in range(1001)]) [6303, 457, 75, 14, 9, 7, 5, 4]

Count maximal layers

def count_maximal_layers(points):

A point (x1,y1) on the two-dimensional plane dominates another point (x2,y2) if bothinequalitiesx1>x2andy1>y2hold.Apointinsidethegivenlistofpointsismaximalifitisnotdominatedbyanyotherpointinthelist.Notethatunlikeinboringoldonedimension,somelistsofpointsmayevencontainpointsthataremaximaldespitethatfactthattheydonotdominateanyother point! A list of points on the two-dimensional plane can contain any number of maximalpoints,whichthenformthemaximallayerforthatparticularlistofpoints.Forexample,thepoints(3,10)and(9,2)formthemaximallayerfor[(1,5), (8,1), (3,10), (2,1), (9,2)].

Givenalistofpointsfromtheupperrightquadrantofthein0initetwo-dimensionalplane,allpointcoordinatesguaranteedtobenonnegative,this functionshouldcounthowmanytimesonewouldhavetoremoveeverypointinthecurrentmaximallayerfromthelistforthatlisttobecomeempty.

Thisisagainoneofthoseproblemswhosepoint(heh)andmotivationismakingthisfunctionfastenoughto0inishreasonablyquicklyevenforalargelistofpoints.Trynottodomuchmoreworkthanisnecessarytoidentifyandremovethecurrentmaximalpoints.Startbynotinghoweachpointcanpotentiallybedominatedonlybythosepointswhosedistancefromtheorigin(0,0)isstrictlylarger.Itdoesn'tevenreallymatterwhichparticulardistancemetricyouuse...

points Expectedresult

[(1, 3), (2, 2), (3, 1)] 1

[(1, 5), (3, 10), (2, 1), (9, 2)] 2

[(x, y) for x in range(10) for y in range(10)] 10

[(x, x**2) for x in range(100)] 100

[(x, x**2 % 91) for x in range(1000)] 28

[((x**3) % 891, (x**2) % 913) for x in range(10000)]

124

Maximum checkers capture

def max_checkers_capture(n, x, y, pieces):

Onceagainwe 0indourselvesonageneralizedn-by-n chessboard, this timeplayingavariationofcheckers where your lone king currently stands at the coordinates (x,y), and the parameterpieces issomekindofset instancethatcontainsthepositionsofallof theopponent'spawns.This function should compute the maximum number of pieces that your king could potentiallycaptureinasinglemove.

Somevariantsofcheckersallowleapingkings thatcancapturepiecesacrossarbitrarydistances.Forsimplicity, inthisproblemkingsaremoresubduedsothattheycaptureapieceonlyonestepawaytothefourdiagonaldirections(thelist[(-1, 1), (1, 1), (1, -1), (-1, -1)]mightcomehandy)assumingthatthesquarebehindtheopponentpieceinthatdiagonaldirectionis vacant. Your king can then capture that piece by jumping over it into the vacant square,immediately removing that captured piece from the board. However, unlike in chess whereeachmove can capture atmost one enemy piece, the chain of captures continues from the newsquare,potentiallycapturingallthepiecesinonedramaticHollywoodswoop.

Themaximumnumber of pieces that can be captured in a singlemove is best computedwith amethodthatlocallyloopsthroughthefourdiagonaldirectionsfromthecurrentpositionoftheking.Foreachsuchdirectionthatcontainsanopponentpiecewithavacantspacebehindit,removethatopponentpiecefromtheboard,andrecursivelycomputethenumberofpiecesthatcanbecapturedfromthevacantsquarethatyourkingjumpsinto.Oncethatrecursivecallhasreturned,restorethecapturedpieceontheboard,andcontinueloopingtothenextdiagonaldirection.

n x y pieces Expectedresult

5 0 2 set([(1,1), (3,1), (1,3)] 2

7 0 0 set([(1,1), (1,3), (3,3), (2,4), (1,5)]) 3

8 7 0 set([(x, y) for x in range(2, 8, 2) for y in range(1, 7, 2)])

9

Collatzy distance

def collatzy_distance(start, goal):

Fromapositiveintegern,youareallowedtomoveintoeither3*n+1orn//2asasinglestep.EventhoughtheseformulaswereobviouslyinspiredbythewonderfullychaoticCollatzconjectureseeninthelectureonunlimitediteration,inthisproblemtheparityofndoesnottieyourhandstousejustoneoftheseformulas;eitherformulacanbeappliedtoanyintegern,regardlessof itsparity.Thisfunctionshoulddeterminehowmanystepsareneededtogetfromstarttogoalbytakingthe shortestpossible route.All suchproblems canbe solvedwithbreadth-0irst search,presentedhereasapreviewforalatercoursethatcoversgraphtraversalalgorithms.(TakethisproblemnowinthesamespiritasyouwouldwatchaMarvelpost-creditsteaser.)

The algorithm visits all integers reachable from start advancing in layers, so that each layerconsistsofintegersatthesamedistancefromthestart.Tobegin,thezerothlayeristhesingletonlist[start],allnumbersat thedistancezero fromstart. (Not toomanyof those!)Then,eachlayerk+1 consistsof integers3*n+1 andn//2 wheren steps through thenumbers in layerk,exceptthatanynumbersalreadyseeninanypreviouslayersareignored.Forexample,ifstart=4,the0irstfourlayersare[4],[13, 2],[40, 6, 7, 1]and[121, 20, 19, 3, 22, 0]forthereachablenumbersatdistances fromzero to three fromthestart, respectively. (Asyouseehere,typicalsearchproblemsseetheselayersgrowingexponentiallyalongk.)

Keep generating layers until thegoal 0irst appears, atwhichpoint you return the current layernumberasyouranswer.(Inpracticalimplementationsofbreadth-0irstsearch,asingle<irst-in-<irst-out queue stores the nodes that the algorithm has discovered but not yet visited, instead ofexplicitlyprocessingeachlayerinaseparateinnerloop.)

start goal Expectedresult

10 20 7

42 42 0

42 43 13

76 93 23

1000 10 9

Van Eck sequence

def van_eck(n):

TheVan Eck sequence problemwasmaking rounds at the timewhile your authorwas updatingthese labspeci0ications.Afterreadingtheproblemonlyhalfwaythrough, itwasalreadyclearthatthiswasgoingtobeoneofthebestsequenceproblemsever.The0irstterminthe0irstpositioni=0equalszero.Theterminlaterpositioniisdeterminedbythetermxinthepreviouspositioni-1:

● Ifthepositioni-1wasthe0irstappearanceofthattermxinthesequencesofar,theterminthecurrentpositioniequalszero.

● Otherwise,iftheprevioustermxhasnowappearedatleasttwiceinthesequence,theterminthecurrentpositioniisgivenbythepositiondifferencei-1-j,wherejisthepositionofthesecondmostrecentappearanceofthetermx.

Thesequencebeginswith0,0,1,0,2,0,2,2,1,6,0,5,0,2,6,5,4,0,5,3,0,3,2,9,...soyouseehowits terms start making repeated appearances right away, especially the zero that automaticallyfollowsthe0irstappearanceofeverynewterm.

In the same spirit as in the earlier problem that asked you to generate terms of the Recaman'ssequence,unlessyouwanttospendtherestofyourdaywaitingfortheautomatedtesterto0inish,this function should not repeatedly bend over backwards to look through the already generatedsequenceforthemostrecentoccurrenceofeachterm.YoushouldratheruseaPythondictionarytoremember the termspreviously seen in the sequence,mapped to thepositionswhere theymadetheirmost recent appearance.With such dictionary, you don't need to explicitly store the entiresequence,butonlytheprevioustermsandpositionsthatarerelevantforyourfuturedecisions.

n Expectedresult

0 0

10 0

1000 61

10**6 8199

10**8 5522779

Tips and trips

def trips_fill(words3, pattern, tabu):

A string of lowercase letters is trip-<illed if every 3-letter substring (here, a “trip”) inside it is athree-letter word from words3, the list of such words in sorted order. Some examples are'pacepad', 'baganami' and 'udianaahunat', with the aid of some of the more obscurethree-letterwordssuchas'cep'and'gan'fromwords_sorted.txt.Givenapatternmadeoflowercaselettersandasterisks,thisfunctionshould0indandreturnthelexicographically<irsttrip-<illedstringthatcanbeconstructedbyreplacingeachasteriskofpatternwithanyletterofyourchoice.Furthermore,noindividualtripmayappearinsidethesolutionmorethanonce.Ifnosolutionexistsforthegivenpattern,returnNone.

Thisproblemisbestsolvedwithrecursionsimilartodecode_morse inthemorse.py example.Thisfunctionshouldloopthroughalltripsthat0itintothe0irstthreecharactersofpattern.(Letbisect_leftbeyourfriendinthistimeofneed.)Foreach0ittingtrip,recursively0illintherestofthepatternfromposition1onwards,withyourcurrentlychosentripstampedintothe0irstthreecharacters of that pattern. As this function needs to return only the 0irst complete solutioninstead of generating all of them, ordinary recursion suf0ices instead of an entire recursivegenerator.Toenforcetheuniquenessof thechosentrips, thisrecursionshouldappend eachtripintothetabulistonthewaydown,andthenpopthattripoutofthetabulistimmediatelyafterreturning.(Inalltoplevelcallsfromthetester,tabuisanemptylist.)

pattern Expectedresult(usingthewordlistwords_sorted.txt)

'**q' 'aeq'

'*yo***' 'iyobaa'

'*m*gv**o' None

'*ef***da**s' 'befloadabas'

'**l**a*l*ai*' 'ablobaalcaid'

'*e'*8 'lekereseyewemeve'

'*'*100 'aaahabaalabbloadabcdfthadcabdeaddtdryadebbsfmtgnubcfibabeamablschaeraboafbibobaccmlxxiseanaambdspace'

Balanced ternary

def balanced_ternary(n):

Theintegertwoanditspowersaboundallovercomputingwhereasthenumberthreeseemstobemostly absent, at least until theory of computation and itsNP-complete problems where thenumber three turns out to be a very different thing from two not only quantitatively, butqualitatively.Steppingfromtwotothreeoftenopensafreshspringofcomputationalcomplexity.

Integersarenormallywrittenoutinbaseten,eachdigitgivingthecoef0icientofthepowerofteninthatposition.Computersinternallyencodeintegersinthesimpler(atleastformachines)binaryofbasetwo.Bothoftheseschemesneedspecialtrickstorepresentnegativenumbersintheabsenceofan explicit negation sign. The balanced ternary representation of integers uses the base threeinsteadof two,withsigned coef0icients from threepossibilities -1, 0 and+1. Every integer, be itpositive or negative, can be broken down into a sumof signed powers of three exactly oneway.Furthermore,thebalancedternaryrepresentationissymmetricaroundzero;therepresentationfor-ncanbetriviallyconstructedby0lippingthesignsofthetermsoftherepresentationof+n.

Givenanintegern,returnthelistofsignedpowersofthreethataddupton,listingthesepowersinthedescendingorderoftheirabsolutevalues.Thisproblemcanbesolvedinafewdifferentways.Thepage"Balancedternary"showsonewaytodothisby0irstconvertingntounbalancedternary(this is justbasethreewithcoef0icients0,1and2,analogoustobinary)andtaking it fromthere.Anotherwaytoachievethesameendisto0irst0indp,thehighestpowerof3thatislessthanequalton.Then,dependingonthevalueofn-p,youeithertakepintotheresultandconvertn-pfortherest,ortake3pintotheresultandconvertn-3pfortherest.AllroadsleadtoRome.

n Expectedresult

5 [9, -3, -1]

-5 [-9, 3, 1]

42 [81, -27, -9, -3]

-42 [-81, 27, 9, 3]

100 [81, 27, -9, 1]

10**8 [129140163, -43046721, 14348907, -531441, 177147, -59049, -19683, -6561, -2187, -729, 243, -81, -9, 1]

Lords of Midnight

def midnight(dice):

Midnightisadicegamewheretheplayerinitiallyrollssixdice,andmustdecidewhichdicetokeepandwhich to re-roll tomaximize his 0inal score. However, all your hardworkwith the previousproblems has now mysteriously rewarded you with the gift of perfect foresight (as some wilyFrenchmanmightsay,youmightunknowinglybeadescendantofMadamedeThebes)thatallowsyoutoforeseewhatpipvalueseachindividualdiewillproduceinitsentiresequenceoffuturerolls,expressedasasequencesuchas[2, 5, 5, 1, 6, 3].Aidedwiththisforesight,yourtaskistoreturnthemaximumtotalscorethatcouldbeachievedwiththegivendicerolls.

Theargumentdiceisalistwhoseeachelementisasequenceofthepipvaluesthatparticulardiewill producewhen rolled. (Since this gamewill necessarily end after atmost six rolls, this givenfuturesequenceneedstobeonlysixelementslong.)Notethattherulesrequireyoutokeepatleastonedieineachroll,whichiswhythetrivialalgorithm“Firstchoosethetwodiceyouusetogetthe1and 4, and add up the maximum pip values for the four remaining dice” does not work, asdemonstratedbythe0irstrowofthefollowingtable.DUCY?

Tomakethetestcasesmoreinteresting,thetesterisprogrammedtoproducefewerones,foursandsixesthantheprobabilitiesofperfectlyfairdicewouldyield.Atacticalplacementofthumbonthescalesoccasionallyhelpstherawrandomnesstohithiddentargetsmoreeffectively.

dice Expectedresult

[[3, 4, 6, 6, 6, 2], [3, 2, 6, 2, 3, 3], [2, 2, 2, 2, 2, 3], [6, 1, 4, 2, 2, 2], [2, 2, 2, 3, 2, 3], [2, 3, 3, 3, 3, 2]]

14

[[2, 6, 2, 5, 2, 5], [5, 3, 3, 2, 5, 3], [2, 2, 2, 2, 5, 2], [3, 6, 3, 2, 2, 5], [6, 2, 2, 6, 3, 2], [2, 2, 3, 2, 2, 2]]

0

[[2, 6, 2, 1, 3, 3], [2, 2, 2, 2, 2, 3], [2, 2, 4, 3, 6, 6], [4, 5, 6, 3, 2, 5], [2, 4, 2, 6, 5, 3], [2, 2, 2, 2, 2, 3]]

17

[[3, 4, 6, 6, 6, 2], [3, 2, 6, 2, 3, 3], [2, 2, 2, 2, 2, 3], [6, 1, 4, 2, 2, 2], [2, 2, 2, 3, 2, 3], [2, 3, 3, 3, 3, 2]]

14

[[2, 3, 5, 3, 2, 2], [1, 3, 2, 3, 6, 4], [3, 2, 3, 3, 3, 5], [3, 6, 4, 6, 2, 3], [2, 3, 3, 2, 3, 2], [3, 5, 3, 5, 1, 2]]

17

Optimal crag score

def optimal_crag_score(rolls):

Anearlierproblemaskedyoutocomputethebestpossiblescoreforasinglerollinthedicegameofcrag.Inthisproblem,thegameisplayedformultiplerolls,againaidedwiththesamegiftofperfectforesightasintheprevious“LordsofMidnight”problem.Giventheentiresequenceofrolls,thisfunctionshouldreturnthehighestpossiblescorethatcanbeachievedwiththoserollsundertheconstraintthatthesamecategorycannotbeusedmorethanonce,asisdictatedbytherulesoftheactualgameofcragthesamewayasinthemorefamousdicegameofYahtzee.

Thegreedyalgorithm“sorttherollsinthedescendingorderoftheirmaximumpossibleindividualscore,andthenuseeachrollforitshighestscoringremainingcategory”doesnotworkhere,sinceseveralrollsmight0itinthesamecategory,andyetarenotequallygoodchoiceswithrespecttotheremaining categories. Therefore, you need to process the list of rolls recursively, each level ofrecursion assigning some still unused category to the current roll. For each such category,recursivelycomputethebestpossiblewaytoassignunusedcategoriestotheremainingrolls.Thebestcategoryforthecurrentrollisthentheonethatmaximizesthesumofthevalueforthecurrentrollandthisrecursivelycomputedsolutionfortheremainingrolls.

Tospeedupthisrecursion,youcankeeptrackofthebestsolutionthatyouhavefoundsofar.Whenthecurrentbranchoftherecursivesearchhasachanceofbeatingthatbestsolution,youcantreatthecurrentbranchashavingasolution,asthereisnopointwastingperfectlygoodprocessorcyclescomputingtheexactvalueofsomethingthatcannotaffectthe0inalanswer.

rolls Expectedresult

[(1, 6, 6), (2, 5, 6), (4, 5, 6), (2, 3, 5)] 101

[(3, 1, 2), (1, 4, 2)] 24

[(5, 1, 1), (3, 5, 2), (2, 3, 2), (4, 3, 6), (6, 4, 6), (4, 5, 2), (6, 4, 5)]

74

[(3, 1, 2), (1, 4, 2), (5, 2, 3), (5, 5, 3), (2, 6, 3), (1, 1, 1), (5, 2, 5)]

118

[(1, 5, 1), (5, 5, 6), (3, 2, 4), (4, 6, 1), (4, 4, 1), (3, 2, 4), (3, 4, 5), (1, 2, 2)]

33

Painted into a corner

def cut_corners(points):

Asintheearlierproblem,forasetofpointsinthetwo-dimensionalintegergrid,acorneristhreepointsoftheexactform(x,y),(x,y+h)and(x+h,y)forsomeh>0foritstipanditstwowings.Givenalistofpointssortedbyx-coordinates,tiesresolvedbyy-coordinates,thisfunctionshouldreturntheminimumnumberofpointswhoseremovalfrompoints makesallcornersdisappear.Obviously, at least oneof the threepoints of every cornermustbe removed.However,wheneverseveral corners share a common point, removing that shared point makes all those cornersdisappear!Thisfunctionshouldthereforebejudiciousinitschoicesofwhichpointstoremove,asthegreedywayisnotalwaystheoptimalway.

This function should start by creating a list of all corners among the givenpoints, each cornerrepresentedasa tuple(i,j,k) of theposition indicesof thepoints that form its tipand itswings.Then,calltherecursivefunctionthatdeterminestheminimumnumberofpointstoremovetogetridofallcorners.Ateachlevelofrecursion,thisfunctionshouldchooseanyoneofremainingcornerswhosethreepointsarestill intact. Itmakesnodifferencewhichcorneryouchoose,sinceyoumustremoveatleastonepointfromeverycorneranyway,eithernoworlater.Asageneralrulein life,whenever there isnochoice insomematter, it canneverharmyou to take thebullby thehornsandjustdoit!Tryremovingeachofthesethreepointsseparatelyinafor-loop,andforeachpotentially removed point, recursively examine the best way to eliminate the corners that stillremaininthatscenario.Outofthosethree,usethebestwaythatworks.

Setsanddictionariesshouldbeusedtospeedupthedecisionmakingatalllevelsofthisrecursion.Furthermore,ifsomecornercontainsatmostonepointthatissharedwithsomeothercorner,thereis littlepoint (heh) inbranching thesearch for thatcorner, sinceremoving thatcornercanneverresultinaworseglobaloutcomethanremovinganyofthetwootherpoints.

points Expectedresult

[(2, 2), (2, 5), (6, 2)] 0

[(2, 2), (2, 5), (5, 2)] 1

[(1, 0), (1, 3), (1, 4), (2, 0), (2, 2), (2, 3), (4, 0), (5, 0)]

3

[(x, y) for x in range(5) for y in range(5)] 8

Go for the Grand: Infinite Fibonacci word

def fibonacci_word(k):

Fibonacci words are strings de0ined analogously to Fibonacci numbers. The recursive de0initionstartswithtwobasecasesS0='0'andS1='01',followedbytherecursiveruleSn=Sn-1Sn-2thatconcatenates the two previous Fibonacci words. See the Wikipedia page for more examples.Especially importantly for this problem, the lengthof eachFibonacciword equals that particularFibonaccinumber.EventhoughwecannotactuallygeneratetheentireFibonacciwordS∞becauseitwouldbein0initelylong,wecanconstructthecharacteratanyparticularpositionkofS∞ina0initenumberofstepsbyrealizingthataftergeneratingsomewordSnthatislongerthank,everylongerwordSmform>n,andthereforealsothein0initewordS∞,muststartwiththeexactsamepre0ixSnandthereforecontainthatsamecharacterinthepositionk.

This function should compute the k:th character of the in0inite Fibonacci word, the positioncountingagainstarting fromzero.Since this is the lastproblemof thisproblemset, tosymbolizeyour reach towards the in0inite as you realize that you can simply ignore the arbitrary laws ofimposedbysocietyofmenasyou,littlestarling,0lyboldlyhighertobidandmakethisgrandslam,yourfunctionmustbeabletoworkforsuchmonstrouslylargevaluesofkthattheymakeevenonegoogol seem likeyoucouldwait itout standingonyourhead.Of course,ouruniversewouldnothaveenoughatomstoencodeSnforsuchalargentoallowyoutolookupitsk:thcharacter.Instead,usetherecursiveformulaandthelistofFibonaccinumbersthatyoudynamicallyexpandasneeded,andridetheself-similarfractalnatureofthein0initeFibonacciwordthroughthe0inishline.

k Expectedresult

0 '0'

1 '1'

10 '0'

10**6 '0'

10**100 + 1 '1'

10**10000 '0'

1234**5678 '0'

Bonus problem 110: Reverse the Rule 110

#for Suzanne: I think that I finally got it nowdef reverse_110(current):

In elementary cellular automata, Rule 110 stands tall for being the only rule proven to becomputationally universal, alongwith itsmirror image counterpart Rule 124. Teetering at theborderlinebetweenchaosandorderwherethereallyinterestingpatternsgettotemporarilyexist,repeated iterations of this Turing-complete rule produce emergent fractal patterns that could,givenenoughtimeandmemory,encodeallpossiblecomputationsthatcanexist.

The functionto iterateanarbitraryelementarycellularautomatonwouldhavemadeanexcellentproblemearlierinthiscollection.Butwedidn’tcomeallthewayuphereforsomethingthattrivial,ohno.Instead,thisfunctionmusteffectivelyoperateinreversebycomputingthepreviousstatefromwhich theRule110wouldproduce thecurrent statewhen appliedone step forward!Asmuchaswewouldliketobeabletoturnbacktime,wecanonlygoforwardwiththearrowoftime.Simulating the reversal of the process usuallymakes this task exponentially harder compared tosimulatingthesameprocessintheforwarddirection.

So that everypositionhas a left and a right neighbour, the left and right edges of each state arecyclicallywrapped together. Tomake the returned answers unambiguous for automated testing,thisfunctionshouldreturnthelexicographicallysmallestoftheprevious statesthatRule110takes to the samecurrent state. Forcurrent states that are impossible toproduce fromanypreviousstatewithRule110(socalledGardensofEden),thisfunctionshouldreturnNone.

Straightforwardcomputationscansuddenlybecomecomplicatedwhenperformedbackwardsfromtheexpected results to thearguments thatwouldproduce those results in the forwarddirection.Thisproblemshouldbesolvedusingaseparaterecursivebacktrackingutilityfunctionto0illintheprevious statefrombeginningtoend.Thebodyoftherecursionshould0irstcheckforcon0lictsbetweenthepreviousandthecurrentstates,andthentryappendingeachofthetwovalues0and1oneatthetime,recursively0illingintherestofthepreviousstateforeachvaluee.

current Expectedresult

[1, 0, 1, 1] [1, 0, 0, 1]

[0, 0, 1, 1, 0] [0, 0, 0, 1, 0]

[0, 1, 0, 1, 0, 1, 1, 1] None

[1, 0, 1, 1, 0, 0, 0, 0] [1, 0, 0, 1, 1, 1, 1, 1]

Bonus problem 111: Aye, eye, I

#for Liz: You made every day a Wednesdaydef wordomino(state, words):

Your nemesis, unceremoniously de-platformed in an earlier problem, has crawled out of Scylla'sjanitorialendinstyleofShawshankRedemption.Havinglearnedherlifelessonaboutcertaindishesbest served with tea and a cookie, your nemesis will now cleverly engage you in a friendlycombinatorialgameof"worddominos"thatthisauthormadeupjustforthisproblem.

Twoplayersmakealternatemovesconstrainedbyasharedlistoflegalfour-letterEnglishwords.Thestate of thegameso far issomestringof letters.Onherturn,eachplayermustextendthecurrentstate with one letter froma to z so that the block of last four characters of this newextended state is oneof the legalwords.However, to guarantee the eventual terminationof thismatch,theblockof lastthreecharactersofthisextendedstatemaynotpreviouslyappearasthatblockanywhereinthecurrentstate.TheplayerunabletoextendthestateonherturnwillfallintotheformlessvoidthatseparatesthiscoursefromitssuccessorCCPS209ComputerScienceII.

Sameas in theearliercombinatorialgameofsubtractingasquare,astate of thisgameishot(winning)ifandonlyifatleastonelegalmovefromthatstateleadstoacold(losing)successorstate.Yourfunctionshouldthereforerecursivelyevaluatethesuccessorstatesthatcanbereachedfromthecurrentstatebyextendingitwithasingleletter.Foracoldstate,thisfunctionshouldreturnNone.Forahotstate,thisfunctionmustreturnitsalphabeticallylowestwinningmovethatleadstoacoldsuccessorstatethatgivesyouropponentnochancetoturnthetide.

With7186four-letterwordsinwords_sorted.txttochoosefrom,thebranchesoftheminimaxsearchtreeforthisgamecanrandomlygetprettydeep.Fortunately,mostofthesemovestendtobepretty much forced (well, at least semi-forced) along the way. This keeps down the effectivebranchingfactor,anddoingsokeepstheeventualrunningtimetolerable.

state Expectedresult

'perp' None

'dunes' 'e'

'tropens' 'e'

'omethangairedeaditalitelaneten' None

'damahabetashagingairana' 'l'

Bonus problem 112: Count domino tilings

#for Tom: Systematic signals rein in unimaginable possibilities def domino_tile(rows):

Indominotilingproblem,aroomofcontiguousunitsquaresistobetessellatedwithblank2-by-1domino tiles, each such tile placed either vertically or horizontally. Of course, this task can bepossible only for even room sizes. This necessary condition by itself does not yet guarantee theexistenceofsometiling,asseeninthefamousmutilatedchessboardproblem.

Inourversionofdominotiling, theshapeoftheroomconsistsofverticallystackedrows thatallsharethecommonstraightlineleftwall.Thelistofrowscontainsthewidthsoftheindividualrows,asmeasuredinsquares.Thisformulationthereforeincludesnotonlytheusualrectangularroomsversionofthisproblem,buteventhemoregeneralYoungdiagramsasaspecialcase.

Thisfunctionshouldcomputethenumberofwaysthattheroomdescribedbygivenrows canbetiledwithdominoes.Aswithallcombinatorialproblemsofthisspirit,thesolutionrequirescarefulconsideration analogous to the Serenity Prayer; since you have no choice about covering everysquareof theroom,youmightaswellgrabthebullbythehornsandrecursively 0ill thatroominorder so that each level of recursion quickly 0inds the 0irst uncovered square. There, recursionbranches in twodirections to tally theways tocomplete the 0illingafterplacingahorizontaloraverticaltileonthatsquare,dependingonwhatyourpreviously0illeddominoesstillallow.Sincethisrecursionexponentiallyrepeatsthesamesubproblemsallovertheplace,somecha-chingschemeisabsolutely necessary to rein in the combinatorial explosion. Once you get the logic workingcorrectly,optimizeeverythingthatyoupossiblycan.

The number of ways to tile the given room generally grows exponentially along the size of thatroom.Someofthesetilingsappearmoreaestheticbyexhibitingsymmetriesorothersuchvisuallypleasantforms.Enumeratingalltilingsunderadditionalaestheticconstraintsmayeitherbeeasierorharderthanenumeratingtheunconstrainedtilings.Foragoodexampleofthisphenomenon,seetheProjectEulerproblem"Tatami-freerooms".

rows Expectedresult

[2, 2] 2

[4, 3, 2, 1] 0

[5, 3, 4, 2] 7

[8, 8, 8, 8, 8, 9, 9] 1895245

[12, 12, 11, 11, 11, 11, 11, 11] 13571985717

[6] * 100 8111122492379632674314680711180748845564827012150625388192928607034509

Bonus problem 113: Invaders must die

#for Ezzat: Intuition beats book learning when stakes get highdef laser_aliens(n, aliens):

Havingescapedfromtheicyn-by-nchessboardintheearlierproblem"Wherenoonecanhearyoubounce", Bishophas called in reinforcements to eliminate the scourge of aliens from this systemonceandforall.Aftertheyarrive,thespacemarinestakepositionssomewherealongtheedgesofthischessboard.Eachmarinewieldsalasercannonthatcanblastasingleshotthroughexactlyoneroworcolumnofthisboard,thatshoteradicatingeveryalienpositionedanywhereonthatroworcolumn.Giventhepositionsofaliens onthisboardasa listof tuples(row, col), sortedbyrowsandbreakingtiesbycolumns,thisfunctionshouldcomputeandreturntheminimumnumberofspacemarinesneededtoeliminateeveryalien.

Thekeyofsolvingthiskindofcombinatorialsearchandoptimizationproblemsliesinrelaxingandallowingthingsthatyoudon'thaveachoiceabouttoconstrainyoursearch, insteadofpointlesslybranchingateveryturntoredundantlyexploreanexponentialnumberofpossibilities.Foranyrowthat still contains aliens, youmust either shoot a laser horizontally through that row, or shoot alaserverticallythrougheverycolumnthatcontainsanalieninthatrow.Thisgivesyouanicetwo-waychoiceforeachrow.Furthermore,duringshootingthroughallthecolumns,cleverupdatinganddowndatingofsomeauxiliarydatastructures,maintainedonthesidethroughouttherecursiontoquicklytellyouthepositionsofthealiensinthegivenrowsorcolumns,willmassivelycurbdownbranchinginfuturerowswithaliensinthosesamecolumns.Youalsohaveachoiceoftheorderinwhichyouprocesstheindividualrows...

n aliens Expectedresult

3 [(0, 1), (0, 2)] 1

4 [(0, 1), (0, 2), (1, 0), (1, 1), (1, 2)] 2

5 [(0, 3), (3, 2), (3, 3), (4, 2)] 2

8 [(1, 4), (3, 6), (4, 6), (4, 7), (5, 0), (5, 4), (5, 6), (5, 7), (7, 0), (7, 7)]

4

10**6 [(42, 42), (999999, 999999)] 2

Bonus problem 114: Stepping stones

#for Suzy: La dureté de deux diamants nous libérera aussidef stepping_stones(n, ones):

Thisproblemisadapted fromtheNumberphilevideo"StonesonanIn0initeChessboard" that thereader should 0irst watch to learn how this excellent puzzle works. To keep this problemmanageable,wewill restrict theplacementofstones intoa 0initen-by-n chessboardwhoseedgesthestonescannotcrossintothevoid.Asusual,rowsandcolumnsarenumberedstartingfromzero.

Starting from stone number 2, consecutively numbered stones are placed on board in ascendingorder so that themoment that the stone number k is placed somewhere, the stones previouslyplacedintoitsuptoeightneighbouringlocationsadduptoexactlyk.Giventheboardsizenandtheinitiallocationsofthebrownones,thisfunctionshouldreturnthehighestnumberedstoneinthelongest sequenceof stones thatcanbeplacedconsecutivelyon theboardwithin therulesof thispuzzle.Forexample,asdemonstratedbyNeilSloane in theabovevideo,youcansnakeup to thestonenumber16whenstartingwithtwobrownstonedplaceddiagonallywithoneemptyspaceinthemiddle,providedthattheboardsizeislargeenoughtocontaintheresultingpattern.However,nomatterhowyoutwistandturn,noplacementofstoneswillgetyouanyfurtherthanthat.

Tospeedupthissearch,youshouldmaintainalistofsetswhosek:thelementisasetofpositionswhosecurrentsumofneighbouringstonesequalsk.Whenplacingthestonenumberkontheboard,yourfunctioncanquicklyloopthroughonlythepositionsinthatparticularset,insteadofexaminingthe entire board each time. Placing a new stone somewhere updates the sums of the currentlyemptycells in itsneighbourhood,making theseneighbouringcells jump fromoneset toanother,andthenjumpbackintotheoriginalsetoncetherecursivesearchtoplacethesequenceofstonesstartingfromthestonek+1hasreturned.

n ones Expectedresult

4 [(0, 0), (3, 3)] 1

5 [(0, 1), (1, 1), (2, 2)] 10

6 [(2, 0), (5, 3), (1, 3), (0, 0)] 19

7 [(4, 4), (1, 2), (6, 5), (1, 5), (4, 2), (1, 4), (4, 5)]

27

8 [(4, 4), (1, 3), (1, 2), (1, 1), (4, 6), (1, 4), (1, 0), (4, 1)]

29