I don't understand how the following code works:
#CodingBat.com Warmup 7
#Given an int n, return True if it is within 10 of 100 or 200.
def near_hundred(n):
return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))
What does "abs()" do? And how does this work to solve the problem above?
You can find out by typing abs
in the interactive prompt:
>>> abs <built-in function abs> >>> help(abs) abs(...) abs(number) -> number Return the absolute value of the argument.
In other words abs
is a built-in function defined such that abs(x)
gives the
absolute value
[1] of x. This means that if x is positive it returns x, otherwise -x. Another way of saying it is that it returns the value of x without the sign.
In your example abs(100 - n)
is the difference between n and 100 expressed as a positive number. You can think of it as the
distance
[2] between n and 100.
It says what it does in your code sample...
#Note: abs(num) computes the #absolute value of a number.
Inbuilt function abs() [1] returns the absolute value of a number. (The numerical value without regard to its sign)
abs(-1) #Returns 1
abs(1) #Also returns 1
[1] http://docs.python.org/library/functions.htmlWhat about this:
- Built-in Functions
The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order.
abs(x)
Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.
[...]
http://docs.python.org/library/functions.html?highlight=abs#abs
this will return absolute value of a number: http://www.tutorialspoint.com/python/number_abs.htm