如何让水仙花数判断函数支持整数、数组、字符串多类型输入?
Hey Steve, let's expand your narcissistic number checker to handle integers, arrays, and string inputs smoothly! Here's a robust solution with step-by-step explanations:
Expanded Narcissistic Number Checker Function
First, a quick recap: a narcissistic number is a number equal to the sum of its own digits each raised to the power of the total number of digits. For example, 153 = 1³ + 5³ + 3³.
Full Implementation Code
def is_narcissistic(input_data): # Step 1: Normalize input into a list of digits and capture original number digits = [] original_num = None if isinstance(input_data, int): # Handle integer input original_num = input_data digits = [int(d) for d in str(input_data)] elif isinstance(input_data, str): # Handle string input (must be a valid numeric string) if not input_data.isdigit(): return False # Swap with `raise ValueError("Invalid numeric string")` for explicit errors original_num = int(input_data) digits = [int(d) for d in input_data] elif isinstance(input_data, list): # Handle array input (all elements must be single-digit integers) if not all(isinstance(d, int) and 0 <= d <= 9 for d in input_data): return False # Swap with `raise ValueError("Array contains invalid digits")` for explicit errors original_num = int(''.join(map(str, input_data))) digits = input_data else: # Unsupported input type return False # Swap with `raise TypeError("Unsupported input type")` for explicit errors # Step 2: Calculate sum of digits raised to the power of digit count digit_count = len(digits) sum_of_powers = sum(d ** digit_count for d in digits) # Step 3: Check if sum matches original number return sum_of_powers == original_num
Key Details
- Input Normalization: We convert all valid input types into a consistent list of digits, while preserving the original number (as an integer) for comparison. This ensures the core logic works the same regardless of input type.
- Flexible Error Handling: The code returns
Falsefor invalid inputs by default, but you can swap those lines withraisestatements if you want explicit error messages instead. - Optimized Core Logic: Reuses the core idea from your original code, but removes unused variables (like the original
total = []) and streamlines the digit-to-power calculation.
Test Cases to Verify
Try these examples to confirm the function works as expected:
is_narcissistic(153)→True(integer input)is_narcissistic("9474")→True(string input)is_narcissistic([1,6,3,4])→True(array input)is_narcissistic("abc123")→False(non-numeric string)is_narcissistic([1, "5", 3])→False(array with non-integer element)
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

