Click here to Skip to main content
15,353,818 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
def isNarcissistic(x):
    """Returns whether or not a given number is Narcissistic.

    A positive integer is called a narcissistic number if it
    is equal to the sum of its own digits each raised to the
    power of the number of digits.

    Example: 153 is narcissistic because 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.
    Note that by this definition all single digit numbers are narcissistic.
narcissistic_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]

for i in narcissistic_numbers:
    assert_true(isNarcissistic(i), str(i) + ' is narcissistic')

non_narcissistic_numbers = [10, 11, 12, 13, 152, 154, 369, 372, 406]

for i in non_narcissistic_numbers:
    assert_true(not(isNarcissistic(i)), str(i) + ' is not narcissistic')

#test existence of docstring
assert_true(len(isNarcissistic.__doc__) > 1, "there is no docstring for isNarcissistic")

What I have tried:

y= 0
for i in range(1, x):
if y==x:
return True
else:return False
Updated 2-Apr-22 9:08am
Richard MacCutchan 2-Apr-22 10:37am
In the above range(1, x) will cause the loop to repeat 153 times. That is not anywhere near what you are trying to do.

Read the task again: It's not the sum of the numbers up to a value, it's teh sum of the cube of the digits in a number.

Hint: The Python Modulo Operator - What Does the % Symbol Mean in Python? (Solved)[^]

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
CPallini 4-Apr-22 2:34am
Please read the task again: it's not teh sum of the cube of the digits in a number, each digit must be raised to the power of N, where N is the count of the digits.
OriginalGriff 4-Apr-22 3:24am
Oops. I was tired ...
How do I solve this narcistic formula

The problem with your code is that it do not try to solve the problem, it is just wrong.
Read carefully the requirement again.
Try to solve each example by hand as a mean to get familiar with the algorithm.

you will need to split the number in its digits. Getting the unit digit is done by getting the reminder of an integer division by 10.
CPallini 4-Apr-22 2:34am
Patrice T 4-Apr-22 5:34am
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900