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

Python函数实现求助:修复check_parity与are_reversed的断言错误

问题修复:实现solutions.py中的两个函数

需要完成solutions.py中两个函数的实现,满足以下要求:

  • check_parity函数:接收数字列表和布尔值两个参数,返回布尔值结果。若第二个参数为True,检查列表所有元素是否为奇数;若为False,检查列表所有元素是否为偶数。
  • are_reversed函数:接收两个列表参数,返回布尔值,判断第二个列表是否与第一个列表反转后相等。

当前运行main.py时出现错误,错误信息如下:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    assert check_parity([1, 2, 3], True) == False
AssertionError

现有代码

main.py代码

from solutions import check_parity, are_reversed
assert check_parity([1, 2, 3], True) == False
assert check_parity([1, 2, 3], False) == False
assert check_parity([0, 2, -4], True) == False
assert check_parity([0, 2, -4], False) == True
assert check_parity([1, 3, -7], True) == True
assert check_parity([1, 3, -7], False) == False
assert are_reversed([1, 2, 3], [3, 2, 1]) == True
assert are_reversed([1, 2, 3], [3, 1, 2]) == False
assert are_reversed([1], [1]) == True
assert are_reversed([], []) == True
assert are_reversed([1, 2, 3], [3]) == False  # na szóstkę
print('All tests passed!')

solutions.py现有代码

def check_parity(list, odd):
  pass

def are_reversed(list1, list2):
  pass

修复后的solutions.py代码

def check_parity(num_list, odd):
    if odd:
        return all(num % 2 != 0 for num in num_list)
    else:
        return all(num % 2 == 0 for num in num_list)

def are_reversed(list1, list2):
    return list1[::-1] == list2

实现说明

  1. check_parity函数:
    • 替换了参数名list(避免覆盖Python内置类型),改为更清晰的num_list
    • 使用all()函数批量判断所有元素是否符合条件:
      • 当odd=True时,验证每个元素是否为奇数(num % 2 != 0,负数奇数同样适用)
      • 当odd=False时,验证每个元素是否为偶数(num % 2 == 0,0属于偶数)
  2. are_reversed函数:
    • 用切片list1[::-1]快速反转列表,直接与第二个列表比较
    • 自动处理空列表、单元素列表、长度不匹配等边界场景

运行修复后的代码后,执行main.py即可输出All tests passed!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:30:33