12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

if arg < res:res = argreturn resdef min2(first, *rest):for arg in rest:if arg < first:first = argreturn firstdef min3(*args):tmp = list(args)tmp.sort( )return tmp[0]# Or, in <strong>Python</strong> 2.4+: return sorted(args)[0]print min1(3,4,1,2)print min2("bb", "aa")print min3([2,2], [1,1], [3,3])All three solutions produce the same result when the file is run. Try typing a few callsinteractively to experiment with these on your own:% python mins.py1aa[1, 1]Notice that none of these three variants tests for the case where no arguments arepassed in. They could, but there’s no point in doing so here—in all three solutions,<strong>Python</strong> will automatically raise an exception if no arguments are passed in. The firstraises an exception when we try to fetch item 0; the second, when <strong>Python</strong> detects anargument list mismatch; and the third, when we try to return item 0 at the end.This is exactly what we want to happen—because these functions support any datatype, there is no valid sentinel value that we could pass back to designate an error.There are exceptions to this rule (e.g., if you have to run expensive actions beforeyou reach the error), but, in general, it’s better to assume that arguments will work inyour functions’ code, and let <strong>Python</strong> raise errors for you when they do not.Bonus pointsStudents and readers can get bonus points here for changing these functions tocompute the maximum, rather than minimum, values. This one’s easy: the first twoversions only require changing < to >, and the third simply requires that we returntmp[-1] instead of tmp[0]. For extra points, be sure to set the function name to“max” as well (though this part is strictly optional).It’s also possible to generalize a single function to compute either a minimum or amaximum value, by evaluating comparison expression strings with a tool like theSpecial Argument-Matching Modes | 337

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!