简体   繁体   中英

need to find greatest number in set that's not greater than given variable

I've got a set, weights and an integer desired weight. I need to remove the element in the list that is closest to, but not greater than desired weight and associate it with actual_weight. Here's what my code looks like thus far:

desired_weight = weights[0]
for i in weights:
 for x in weights:
    if x>i:
        if desired_weight <= x:
            actual_weight = desired_weight
            weights.remove()

假设我了解您的要求,

actual_weight = max([x for x in weights if x <= desired_weight])

You can try this:

desired_weight = weights[0]
diff = inf
actual_weight = 0
for x in weights:
  if x < desired_weight and (x-desired_weight) < diff:
    diff = x - desired_weight
    actual_weight = x

weights.remove(actual_weight)
actual_weight = max([x for x in weights if x <= desired_weight])
weights.remove(actual_weight)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM