如何检测嵌套列表中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']为例:
- 遍历前两个HWY,连续长度累加到2
- 遇到FAC时,计算
2²=4计入行得分,连续长度重置为0 - 遍历到最后一个HWY,连续长度累加为1
- 行遍历结束,补算
1²=1计入行得分,该行总得分5,符合预期结果。
内容的提问来源于stack exchange,提问作者user16472631
相关产品推荐
相关产品推荐

