For example I have a non-ordered list of values [10, 20, 50, 200, 100, 300, 250, 150]

I have this code which returns the next greater value:

def GetNextHighTemp(self,  temp,  templist):
    target = int(temp)
    list = []
    for t in templist:
        if t != "":
            list.append(int(t))
    return str(min((abs(target - i), i) for i in list)[1])

e.g. If temp = 55, it will return '100'.

But how can I get the lesser of the value? That is how to get it to return '50'?

Thank you.

Recommended Answers

All 4 Replies

Please do not override the builtin type as variable name.

It doesn't work as you said, when I pass 55 it returns 50, and for 85 it returns 100. In fact it returns the closest value. I would suggest

max((x for x in templist if int(x) <= target))

Remark that this will raise ValueError if target is smaller than all the list's element.

well then he can try and except the error gracefuly cant he?

tonyjv, yes, thank you, I haven't realised it was a built-in type as the Eclipse text highlighter didn't highlight it.
I've finally got it:

try:
        templist = QStringList()
        for material in self.materials:
            if material.attrib["name"] == matvar:
                temps = material.getiterator("temp")
                for temp in temps:
                    templist.append(temp.text)
        templist.sort()
        target = int(tempvar)
        x1 = max(int(t) for t in templist if t != '' and int(t) < target)
        x2 = min(int(t) for t in templist if t != '' and int(t) > target)
        return [x1, x2]
    except Exception, inst:
        return "0"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.