YouTip LogoYouTip

Python Narcissistic Check

## Python: How to Check if a Number is Narcissistic In number theory, a **Narcissistic number** (also known as a **pluperfect digital invariant (PPDI)**, an **Armstrong number**, or a **plusperfect number**) is a number that is the sum of its own digits each raised to the power of the number of digits. For example, $153$ is a 3-digit narcissistic number because: $$1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153$$ Similarly, $1634$ is a 4-digit narcissistic number because: $$1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634$$ This tutorial will guide you through implementing a clean, efficient Python function to check whether a given integer is a Narcissistic number. --- ## The Algorithm To determine if a number is narcissistic, we follow these steps: 1. Convert the integer to a string to easily access each individual digit. 2. Determine the total number of digits ($n$) by measuring the length of the string. 3. Convert each character back to an integer, raise it to the power of $n$, and sum these values. 4. Compare the calculated sum with the original number. If they are equal, the number is narcissistic. --- ## Code Implementation Here is the standard Python implementation using a list comprehension and the built-in `sum()` function. ```python def is_narcissistic_number(num): # Convert the number to a string to access individual digits num_str = str(num) # Get the total number of digits (n) n = len(num_str) # Calculate the sum of each digit raised to the power of n sum_of_powers = sum(int(digit) ** n for digit in num_str) # Return True if the sum equals the original number, otherwise False return sum_of_powers == num # --- Test the function --- number = 153 if is_narcissistic_number(number): print(f"{number} is a Narcissistic number") else: print(f"{number} is NOT a Narcissistic number") ``` ### Output ```text 153 is a Narcissistic number ``` --- ## Code Explanation 1. **`num_str = str(num)`**: Converts the integer input into a string. This allows us to iterate through each digit as a character. 2. **`n = len(num_str)`**: Finds the length of the string, which represents the number of digits ($n$). 3. **`sum(int(digit) ** n for digit in num_str)`**: - Iterates through each character (`digit`) in the string. - Converts the character back to an integer using `int(digit)`. - Raises it to the power of $n$ using the exponentiation operator (`**`). - Sums all the powered values together using Python's highly optimized `sum()` function. 4. **`return sum_of_powers == num`**: Performs a boolean comparison. If the sum matches the original input, it returns `True`; otherwise, it returns `False`. --- ## Advanced Use Case: Finding Narcissistic Numbers in a Range You can easily use this helper function to find all Narcissistic numbers within a specific range (for example, all 3-digit narcissistic numbers between 100 and 999): ```python # Find all 3-digit Narcissistic numbers narcissistic_numbers = [x for x in range(100, 1000) if is_narcissistic_number(x)] print("3-digit Narcissistic numbers:", narcissistic_numbers) ``` ### Output ```text 3-digit Narcissistic numbers: [153, 370, 371, 407] ``` --- ## Performance Considerations * **Time Complexity**: $\mathcal{O}(d)$ where $d$ is the number of digits in the integer. Since $d = \lfloor\log_{10}(num)\rfloor + 1$, the execution time is extremely fast for standard integer types. * **Space Complexity**: $\mathcal{O}(d)$ to store the string representation of the number. * **Alternative Mathematical Approach**: If you want to avoid converting the number to a string, you can extract digits mathematically using modulo (`% 10`) and floor division (`// 10`) operations in a loop. However, the string conversion method shown above is generally preferred in Python for its readability and conciseness.
← Python Find Duplicates ListPython Substring Position β†’