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
midas 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), somidends 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
nto an integernum, then tried to slice it like a string withnum(val[:mid])—integers don't support slicing, andvalis the length of the number, not the number's string form. This would throw aTypeErrorimmediately. - Confusing variable roles: Your
valvariable 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
- String Conversion: Turning the input number into a string lets us easily slice it into halves and iterate over each digit.
- Proper Midpoint:
midpoint = total_length // 2gives 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. - 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.
- Equality Check: Finally, we just compare the two sums and return the result.
内容的提问来源于stack exchange,提问作者Mayur Potdar
相关产品推荐
相关产品推荐

