ThegetRange () example wPt work mly if the membere boosed to it are in the range of min andmax. To make it more gemml purpose, we can use nthee of the following :
from java.lang import Double from java.lang import Double and then either of them:
min = Double.MAX_VALUE max = Double.MIN_VALUE min = Integer.MAX_VALUE max = Integer.MIN_VALUE
This will make the function work well with Integer or Double types. The question is how well it will work with Long types. We'll have our answer shortly.
To figure min and max,getRange () tterates rllroegP He nums sequence.
for item in nums:
if (item > max): max = item if (item < min): min = item
The expression item > max determines if the item's value is greater than max. If so, max is assigned to it, as expressed by this compound statement:
The following compound stdteme nl indicates that the item's; value is lesr rhan min eo it's ^signed to min: if (item < min): min = item
When the loop stops iterating Sllroughthe valuss, getRange () returns min,max, and max-min (range). return (min, max, max-min)
The approach just described is a simple one, but it has a flaw. It works only if the numbers passed to xrange () are within max-min. The solution is the nums variable, which is a sequence with an intrinsic operation (otherwise known as a built-in function) for finding mi n and max in a list, nums is an improvement overgetRange () because it's much shorter and can work with all numeric types as well as all Longs, Floats, and Doubles at their maximum range of precision. With nums there's no for loop and no figuring out what max and min should be initialized to (that is, given a default value).
Here's an example of nums:
def getRange2 (nums):
Was this article helpful?