Codality Python MaxProductOfThree练习出现TypeError: 'function' object is not subscriptable错误的修复请求
Hey there, let's break down and fix the error you're seeing:
The Root Cause
That TypeError: 'function' object is not subscriptable happens because you tried to call your solution function using square brackets [] instead of the required parentheses () for function calls. On top of that, you also forgot to wrap your input array in square brackets when passing it in.
Fixed Code
Here's the corrected version of your code:
def solution(A): A.sort() N = len(A) # Case 1: Two smallest negatives (their product is positive) * largest positive P1 = A[N-1] * A[0] * A[1] # Case 2: Product of the three largest numbers P2 = A[N-1] * A[N-2] * A[N-3] return max(P1, P2) # Fixed function call with parentheses and properly formatted array print(solution([4,2,2,5,1,5,8]))
Quick Notes on Your Logic
Great job on the core logic here! Sorting the array and checking those two cases covers all possible scenarios for the maximum triplet product:
- When two large negative numbers multiply to a big positive, then multiplied by the largest positive in the array
- When the three largest positive numbers give the biggest product
This works for all valid input arrays (non-empty, as per the problem statement). For example, if you test with the sample input [-3, 1, 2, -2, 5, 6], the function correctly returns 60.
内容的提问来源于stack exchange,提问作者user12253044

