1

So I'm trying to write a function that says if x is less than lo, return low; returns hi if x is greater than hi; and returns x otherwise. How would I write that without using conditionals, only using the min and max functions. So far I have the first two statements down:

print max(x, lo)
print min(x, hi)

However, I just can't seem to get the returning of x if neither of the previous to statements are false.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
TrigonDark
  • 184
  • 2
  • 9
  • 1
    Why not just write with conditionals and move on? Writing clever and succinct code is rewarding to you but it is difficult to read, even if it is yourself that must revisit the code six months from now to make a change. – Brian Ogden Jun 25 '13 at 00:17
  • 1
    @Brian probably because this is a homework question that pops up now and again that's designed to make the student think of how to nest the functions... ;) – Jon Clements Jun 25 '13 at 00:17
  • I just don't get why people ask homework questions. If I was paying for a class, I'd expect to get my money's worth out of it, and expect my professor to teach me stuff instead of random people on the internet. I thought the whole point of taking a class was to learn stuff. – Crowman Jun 25 '13 at 00:55
  • @paul in a way I agree Paul but I think the larger statement to make is why are they teaching stuff like this in school, perhaps mental exercises on the subject you can say, but I would imagine you can teach only things you need for the real world and students will learn and also be more successful faster. – Brian Ogden Jun 26 '13 at 18:03

1 Answers1

4

Try this:

min(max(x,lo),hi)

max gives x a lower bound, and min gives x an upper bound.

This is just an equivalent way of writing a conditional.

simonzack
  • 19,729
  • 13
  • 73
  • 118