Python实现4x4网格上下相邻元素和等于指定值的检测求助
Hey there! Let's get your code sorted out. I see you're trying to check if any vertically adjacent pairs in a 4x4 grid add up to a target value (like 2048), and ran into that pesky "list indices must be integers or slices, not tuples" error. Let's break down what went wrong and simplify your solution.
First, the Root Cause of Your Error
The main issue is how you're accessing elements in your 2D list. In Python, to get the element at row i and column j, you need to write a[i][j], not a[i,j]. The comma syntax tells Python you're passing a tuple as an index, which isn't valid for lists—hence the error you saw.
Simplifying the Solution (Focused on Vertical Pairs)
Your original code was overcomplicating things by checking horizontal neighbors too, but the problem only asks for 上下相邻(vertical) pairs. Here's a clean, efficient version that does exactly what you need:
# Your 4x4 grid grid = [[2, 1024, 8, 8], [4, 1024, 16, 32], [2, 32, 64, 128], [8, 256, 2, 2]] def has_vertical_sum(grid, target): # Iterate over each column for col in range(len(grid[0])): # Iterate over each row except the last one (no row below it) for row in range(len(grid) - 1): # Check sum of current element and the one directly below it if grid[row][col] + grid[row + 1][col] == target: return True # If no matching pairs found after all checks return False # Test with target 2048 (your example) assert has_vertical_sum(grid, 2048) == True, "No vertical pairs sum to 2048!"
Why This Works Better:
- Target as a Parameter: Instead of hardcoding 2048, we pass it as an argument—this makes the function reusable for any target value.
- Efficient Traversal: We only check each vertical pair once. Since we don't need to check the last row (there's no row below it), we use
range(len(grid) - 1)to avoid unnecessary iterations. - Early Exit: As soon as we find a valid pair, we return
Trueimmediately—no need to check the rest of the grid. - Proper List Indexing: Uses
grid[row][col]to correctly access 2D list elements, fixing your original error.
What Was Wrong With Your Original Code:
- Incorrect Indexing:
a[i,j]is invalid for lists—usea[i][j]instead. - Unnecessary Checks: You were checking horizontal neighbors (left/right) which the problem didn't require.
- Hardcoded Target: Tying the function to 2048 limits its usefulness.
- Case Sensitivity: Python requires uppercase
Falsefor boolean values (you wrotereturn falsewhich would throw another error).
In your grid, the pair at (0,1) and (1,1) (1024 + 1024) sums to 2048, so the assert will pass successfully!
内容的提问来源于stack exchange,提问作者Lanny Magnet

