Python 2.7 - 57 chars
i=`input()`
print`sum(map(lambda x:int(x)**len(i),i))`==i
There is a shorter Python answer, but I might as well toss in my contribution.
i=`input()`
i
is set to input()
surrounded by backticks (which is surprisingly hard to type through SE's markdown interpreter). Surrounding x
with backticks is equivalent to str(x)
. [backtick]input()[backtick]
saves two characters over raw_input()
in any case where we can assume the input is an int, which we're allowed to do:
Error checking for text strings or other invalid inputs is not required.
Once i
is a string containing the user's input, the next line is run. I'll explain this one from the inside out:
map(lambda x:int(x)**len(i),i)
map
is a function in Python that takes a function and an iterable as arguments and returns a list of each item in the iterable after having the function applied to it. Here I'm defining an anonymous function lambda x
which converts x
to a string and raises it to the power of the length of i
. This map
will return a list of each character in the string i
raised to the correct power, and even nicely converts it to an int for us.
`sum(map(lambda x:int(x)**len(i),i))`
Here I take the sum of each value in the list returned from the map
. If this sum is equal to the original input, we have a narcissistic number. To check this, we either have to convert this sum to a string or the input to an int. int()
is two more characters than two backticks, so we convert this to a string the same way we did with the input.
print`sum(map(lambda x:int(x)**len(i),i))`==i
Compare it to i
and print the result, and we're done.
True
if it's such a number, but anything else (in this case the number itself) if not? \$\endgroup\$