You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让水仙花数判断函数支持整数、数组、字符串多类型输入?

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 False for invalid inputs by default, but you can swap those lines with raise statements 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:20:28