tags:

views:

378

answers:

5

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?

+3  A: 

Inbuilt function abs() returns the absolute value of a number. (The numerical value without regard to its sign)

abs(-1) #Returns 1
abs(1)  #Also returns 1
Tim
+16  A: 

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 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 between n and 100.

Mark Byers
Great answer, I'll accept this answer when the 5 minutes are up. Thanks!
Serg
Nice answer... teach a man to fish!
Nik Reiman
+1 even though it's a terrible answer. "#Note: abs(num) computes the #absolute value of a number." was in the code. Why do all this "thinking" and "typing" when one could simply read?
S.Lott
@S.Lott: *+1 even though it's a terrible answer.* Ermm.....?? *Why do all this "thinking" and "typing" when one could simply read?* - Code comments aren't always accurate. And he might not have known what "absolute value" meant...
Mark Byers
@Mark Byers: And the on-line help will define absolute value in more more *Principia Mathematica* way? The comments sure seem to be precisely and completely focused on being explanatory. While your answer is a great answer (deserving at least 10 upvotes) it totally misses the hilarious silliness of someone who did not actually read the actual comments and merely posted code with a dumb question.
S.Lott
+2  A: 

What about this:

  1. 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

sleske
A: 

this will return absolute value of a number: http://www.tutorialspoint.com/python/number_abs.htm

Keshan
+9  A: 

It says what it does in your code sample...

#Note: abs(num) computes the #absolute value of a number.

Jimmy
+1: Hilarious. Multi-upvotes are deserved.
S.Lott
+1 for pointing out that the answer was in the question.
John