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

Python实现4x4网格上下相邻元素和等于指定值的检测求助

Fixing Your 2048 Vertical Pair Check Code

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 True immediately—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—use a[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 False for boolean values (you wrote return false which 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:35:48