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

Python3.6报错TypeError: 'int' object is not subscriptable求解决

Fixing Your Number Split and Sum Comparison Code

Let's walk through the issues in your code and fix them so it works as intended:

Key Problems in Your Original Code

  • Incorrect midpoint calculation: You're calculating mid as half the length of the string representation of the number's length—that's totally not what you need. For example, if your number is 123435 (length 6), str(val) becomes "6" (length 1), so mid ends up as 0, which breaks the split entirely. You should instead split based on half the original number's length.
  • Trying to slice an integer: You converted n to an integer num, then tried to slice it like a string with num(val[:mid])—integers don't support slicing, and val is the length of the number, not the number's string form. This would throw a TypeError immediately.
  • Confusing variable roles: Your val variable holds the length of the number, but you tried to use it as if it were the number's string representation, which led to invalid operations.

Corrected Code

def isEqual(n):
    # Convert the input to a string to easily access individual digits
    num_str = str(n)
    # Get the total length of the number and calculate the split midpoint
    total_length = len(num_str)
    midpoint = total_length // 2
    
    # Calculate sum of digits in the first half
    first_half_sum = sum(int(digit) for digit in num_str[:midpoint])
    # Calculate sum of digits in the second half
    second_half_sum = sum(int(digit) for digit in num_str[midpoint:])
    
    # Return whether the two sums are equal
    return first_half_sum == second_half_sum

# Test cases
print(isEqual(123435))  # Outputs False (6 vs 12)
print(isEqual(123321))  # Outputs True (6 vs 6)

How This Works

  1. String Conversion: Turning the input number into a string lets us easily slice it into halves and iterate over each digit.
  2. Proper Midpoint: midpoint = total_length // 2 gives us the correct split point—for a 6-digit number, this splits it at index 3, giving us the first 3 digits and last 3 digits.
  3. Sum Calculation: Using a generator expression, we convert each character in the sliced string back to an integer and sum them up. This is clean and efficient for this use case.
  4. Equality Check: Finally, we just compare the two sums and return the result.

内容的提问来源于stack exchange,提问作者Mayur Potdar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:16:18