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

判断指定Python函数是否能生成符合要求的犁地移动路径

代码能否生成指定的移动路径列表?

需求说明:
需要编写函数读取嵌套列表field,实现:

  • 偶数行(索引0、2、4…)从左到右移动,路径坐标为(列索引, 行索引),列索引从0到行长度-1
  • 奇数行(索引1、3、5…)从右到左移动,路径坐标为(列索引, 行索引),列索引从行长度-1到0
    最终返回由这些坐标元组组成的路径列表。

用户提供的代码:

def reverse_list(input_list):
    list_reversed = input_list[::-1]
    return list_reversed

def student_function(field):
    plough_movements = []

    for row_index, row in enumerate(field):
        if row_index % 2 == 0:
            plough_movements.extend([(col, row_index) for col in range(len(row))])
        else:
            reverse_row = reverse_list(row)
            plough_movements.extend([(col, row_index) for col in range(len(reverse_row))])

    return plough_movements

指定的目标结果(示例):

[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 4), (1, 3), (1, 2), (1, 1), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 4), (3, 3), (3, 2), (3, 1), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (5, 4), (5, 3), (5, 2), (5, 1), (5, 0), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (7, 4), (7, 3), (7, 2), (7, 1), (7, 0), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (9, 4), (9, 3), (9, 2), (9, 1), (9, 0)]

代码问题分析

这段代码无法生成指定的结果列表,问题出在奇数行的处理逻辑:

  • 代码中对奇数行执行了reverse_list(row)反转行内容,但后续生成坐标时,仍然使用range(len(reverse_row))生成从0开始的列索引,最终得到的坐标是(0, 1), (1, 1), ..., (4, 1),和目标结果中奇数行的(4, 1), (3, 1), ..., (0, 1)完全相反。
  • 反转行内容本身没有意义,因为我们需要的是调整列索引的遍历顺序,而非行内元素的顺序。

修正方案

不需要反转行内容,直接对奇数行的列索引进行倒序遍历即可:

def student_function(field):
    plough_movements = []

    for row_index, row in enumerate(field):
        if row_index % 2 == 0:
            plough_movements.extend([(col, row_index) for col in range(len(row))])
        else:
            # 直接倒序生成列索引
            plough_movements.extend([(col, row_index) for col in reversed(range(len(row)))])

    return plough_movements

内容的提问来源于stack exchange,提问作者Dada 'Foluso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:26:25