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

如何检测嵌套列表中HWY是否相邻并按规则计算对应点数

HWY点数统计代码修正方案

核心逻辑

逐行统计连续HWY的段长,每段按段长²计算得分后累加,避免直接对整行HWY总数量取平方的错误。

代码实现

原有错误代码示例(仅作对比)

total = 0
for row in map1:
    hwy_total = row.count('HWY')
    total += hwy_total ** 2

修正后代码

total_score = 0
for row in map1:
    current_consecutive = 0
    row_total = 0
    for cell in row:
        if cell == 'HWY':
            current_consecutive += 1
        else:
            if current_consecutive > 0:
                row_total += current_consecutive ** 2
                current_consecutive = 0
    # 补全行末尾连续HWY的统计
    if current_consecutive > 0:
        row_total += current_consecutive ** 2
    total_score += row_total

效果验证

以你给出的测试行['HWY','HWY','FAC','HWY']为例:

  1. 遍历前两个HWY,连续长度累加到2
  2. 遇到FAC时,计算2²=4计入行得分,连续长度重置为0
  3. 遍历到最后一个HWY,连续长度累加为1
  4. 行遍历结束,补算1²=1计入行得分,该行总得分5,符合预期结果。

内容的提问来源于stack exchange,提问作者user16472631

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 01:12:03