Home > Software engineering >  What is wrong with my narcissistic function in python?
What is wrong with my narcissistic function in python?

Time:08-06

Explanation of the challenge

A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

For example, take 153 (3 digits), which is narcissistic;

1^3   5^3   3^3 = 1   125   27 = 153

The Challenge:

Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10. This may be True and False in your language, e.g. PHP.

Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function.

My code;

def narcissistic( value ):

    macht = len([int(a) for a in str(value)])
    fractioneren = [int(a) for a in str(value)]

    for i in range(macht):
        fractioneren[i] = fractioneren[i]**macht

    print(sum(fractioneren)==value)

The tests;

test.assert_equals(narcissistic(7), True, '7 is narcissistic');
test.assert_equals(narcissistic(371), True, '371 is narcissistic');
test.assert_equals(narcissistic(122), False, '122 is not narcissistic');
test.assert_equals(narcissistic(4887), False, '4887 is not narcissistic');

Test Results:

Log
True
7 is narcissistic; None should equal True
Log
True
371 is narcissistic; None should equal True
Log
False
122 is not narcissistic; None should equal False
Log
False
4887 is not narcissistic; None should equal False

CodePudding user response:

I tried out your code. It looks like you just need to convert your "value" parameter to an "int" as follows:

print(sum(fractioneren)==int(value))

When I tried that out, I got a value of "True" for 371 and other such numbers.

@Una:~/Python_Programs/Narc$ python3 Narc.py 
Enter a number:371
True
Enter a number:7
True
Enter a number:153
True
Enter a number:122
False

Give that a try.

CodePudding user response:

Alternatively, you could simplify the code by directly stringify the number then compute the sum of powers, but choose more meaningful variable names:

Then once it's done with computing, it just checks if the summed total equals the number. By comparison and return the verdict!

def isNarcissisticNum(n):
    lens = len(str(n))
    tot = 0
    for d in str(n):
        tot  = int(d) ** lens
        
    return tot == n              # check if the total sum is matching
  • Related