0

Stuck on python problem

Given a set, weights, and an integer desired_weight, remove the element of the set that is closest to desired_weight (the closest element can be less than, equal to OR GREATER THAN desired_weight), and associate it with the variable actual_weight. For example, if weights is (12, 19, 6, 14, 22, 7) and desired_weight is 18, then the resulting set would be (12, 6, 14, 22, 7) and actual_weight would be 19. If there is a tie, the element LESS THAN desired_weight is to be chosen. Thus if the set is (2, 4, 6, 8, 10) and desired_weight is 7, the value chosen would be 6, not 8. Assume there is at least one value in the set. This is what I have for the code: actual_weight = (lambda x: [x, weights.remove (x) ] [0] ) (max(x for x in weights if x < desired_weight) ) or (lambda x: [x, weights.remove (x) ] [0] ) (abs(x for x in weights if x == desired_weight) ) or (lambda x: [x, weights.remove (x) ] [0] ) (min(x for x in weights if x > desired_weight) But it is not working. I’ve tried half a dozen different things, and this is the only one I’ve come close to solving the problem with. Am I over thinking things? Thanks everybody.

8th Sep 2020, 10:33 AM
Donovan
2 Réponses
+ 1
that one didnt work afterall. but after some tinkering this is what i discovered worked: actual_weight=None for e in weights: if actual_weight==None or (abs(e-desired_weight)<abs(actual_weight-desired_weight)) or (abs(e-desired_weight) == abs(actual_weight-desired_weight) and e<desired_weight): actual_weight=e weights.remove(actual_weight)
8th Sep 2020, 3:39 PM
Donovan
+ 1
Yeah this looks like it may work. I won’t be able to check till tonight but thank you!
8th Sep 2020, 12:26 PM
Donovan