We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#!/bin/python3fromcollectionsimportdequefromosimportenvirondefequalStacks1(*args)->int:"""Find the maximum possible height such that all stacks are of equal height."""heights=[*map(sum,args)]whilenotall(height==heights[0]forheightinheights):heights[(i:=heights.index(max(heights)))]-=args[i].popleft()returnheights[0]defequalStacks2(h1:deque[int],h2:deque[int],h3:deque[int])->int:"""Find the maximum possible height such that all 3 stacks are of equal height."""s1,s2,s3=map(sum,(h1,h2,h3))whilenot(s1==s2==s3):ifs1==(tallest:=max(s1,s2,s3)):s1-=h1.popleft()elifs2==tallest:s2-=h2.popleft()else:s3-=h3.popleft()returns3classStack(deque):"""Stack that tracks height"""__slots__={"height"}def__init__(self,values:deque[int])->None:"""Initialize a stack and calculate height."""super().__init__(values)self.height=sum(values)def__repr__(self)->str:"""Return a representation of a Stack object."""returnf"{self.__class__.__name__}(values={list(self)})"defpop(self)->int:"""Pop the first index and update height."""try:popped=self.popleft()exceptIndexError:returnNoneself.height-=poppedreturnpoppeddefequalStacks3(*args)->int:"""Find the maximum possible height such that all stacks are of equal height.UsesaStackclassthattracksheight"""stacks:list[Stack]=sorted(map(Stack,args),key=(height:=lambdastack:stack.height))while(min_height:=stacks[0].height)!=(max_height:=stacks[-1].height):whilemax_height>min_height:max_height-=stacks[-1].pop()stacks.sort(key=height)returnmax_heightdefequalStacks_recursive(*args)->int:"""Recursivelyfindthemaximumpossibleheightsuchthatallstacksareofequalheight.UsesaStackclassthattracksheight"""height=args[0].heightifall(stack.height==heightforstackinargs):returnheightargs.sort(key=lambdastack:stack.height)args[-1].pop()returnequalStacks_recursive(*stacks)defequalStacks4(*args)->int:"""Find the maximum possible height such that all stacks are of equal height.Usesarecursivestrategy"""returnequalStacks_recursive(*map(Stack,args))defequalStacks(*args,strategy=equalStacks4)->int:"""Usingthegivenstrategy,findthemaximumpossibleheightsuchthatall3stacksareofequalheight.Alsoassertsthatthestrategiesreturnthesameresult"""assert(equalStacks1(*args)==equalStacks2(*args)==equalStacks3(*args)==equalStacks4(*args))returnstrategy(*args)if__name__=="__main__":input()result:int=equalStacks(*map(lambdaintegers:deque(map(int,integers.rstrip().split())),(input(),input(),input()),))withopen(environ["OUTPUT_PATH"],"w")asf:f.write(f"{result}\n")
All four strategies pass all test cases. All strategies except the second are also agnostic to the number of stacks. The third and fourth strategies utilize an OOP approach. The fourth strategy is recursive. The common theme is that stack heights are summed just once and then updated by the cylinder height each time a cylinder is popped from the tallest stack.
I also refactored the if __name__ == "__main__": block. Notably, deque.popleft() is much faster than list.pop(0).
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Equal Stacks
You are viewing a single comment's thread. Return to all comments →
Here are some Python 3 solutions:
All four strategies pass all test cases. All strategies except the second are also agnostic to the number of stacks. The third and fourth strategies utilize an OOP approach. The fourth strategy is recursive. The common theme is that stack heights are summed just once and then updated by the cylinder height each time a cylinder is popped from the tallest stack.
I also refactored the
if __name__ == "__main__":
block. Notably,deque.popleft()
is much faster thanlist.pop(0)
.