#### Challenge ### # If a canoe can hold up to 2 robots, or a max weight of 150 lbs, how do you determine the minimum # canoes needed? # Inputs: list of robot weights. import math import random def numCanoes(weightsList): '''Given list of integers of robot weights, determine # canoes needed.''' # Return early if bad data. if weightsList == [] or None: return 0 # Cleanup data: remove overweight robots. cleanWeights = [weight for weight in weightsList if weight<=150 and weight>0] cleanWeights = sorted(cleanWeights,reverse=True) # print "New Sorted array:", cleanWeights # Compute sum of weights. sumWeights = 0 for weight in cleanWeights: sumWeights+=weight '''Algorithm 1. # Hacked together during our call. canoes = math.ceil(sumWeights/150) #This rounds up. canoesByPairs = math.ceil(float(len(cleanWeights))/2) if canoesByPairs > canoes: return canoesByPairs ''' # Algorithm 2. # Read each sorted value. # If current robot is 150, add a canoe. # If the robot weight is less than 150, read the next robot, if both are less than 150, add a canoe. Update pointer to third element. # If the robot weight is less than 150, read the next robot, if it sums to greater than 150, add a canoe. # If pointer passes len, break. # If pointer equals len, add a canoe then break. canoes = 0 pointer = 1 for i in range(len(cleanWeights)): if pointer>=len(cleanWeights): if pointer==len(cleanWeights): canoes+=1 break elif pointer>=len(cleanWeights): break if cleanWeights[pointer-1]==150: canoes +=1 elif (cleanWeights[pointer-1]+cleanWeights[pointer])<=150: canoes+=1 pointer+=1 else: canoes+=1 pointer+=1 return canoes case1 = [150,300, 500] #1 case2 = [150,300,75,75,500,130,30] #4 case3 = [1, 1, 1, 1, 1, 1, 1] #4 case4 = [] #0 case5 = [148, 1, 148, 1, 1, 150] #<-- ceil(449/150) =>3, len/2 => 3, ans=4 case6 = [500,1000] #0 case7 = [random.randint(0,300) for i in range(15)] print case7 print "Test case1", case1, "--> ", numCanoes(case1), "Canoes Needed." print "Test case2", case2, "--> ", numCanoes(case2), "Canoes Needed." print "Test case3", case3, "--> ", numCanoes(case3), "Canoes Needed." print "Test case4", case4, "--> ", numCanoes(case4), "Canoes Needed." print "Test case5", case5, "--> ", numCanoes(case5), "Canoes Needed." print "Test case6", case6, "--> ", numCanoes(case6), "Canoes Needed." print "Test case7", case7, "--> ", numCanoes(case7), "Canoes Needed."
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question