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

Python面向对象示例中计算两个Sector扇形交集及AssertionError修复

解决方案

核心问题说明

你触发AssertionError的直接原因是intersect方法当前返回三元组,不符合方法定义要求的Sector类型返回值,校验逻辑调用str()时会优先使用你定义的Sector.__str__方法,元组转字符串的结果自然无法匹配预期格式。

交集计算规则

题目明确两个扇形必有非空交集,因此交集的三个属性计算逻辑为:

  • 起始角度fr:取两个扇形起始角度的较大值
  • 结束角度to:取两个扇形结束角度的较小值
  • 半径rad:取两个扇形半径的较小值

修正后代码

仅修改intersect方法的代码:

def intersect(self, other: Sector)-> Sector:
    '''Returns a new sector that is the result of the intersection of this sector with the other one. For simplicity, assume that the two sectors have non-empty intersection (overlap).'''
    new_sector = Sector()
    new_sector.fr = max(self.fr, other.fr)
    new_sector.to = min(self.to, other.to)
    new_sector.rad = min(self.rad, other.rad)
    return new_sector

额外可选修正(现有方法逻辑漏洞)

你当前代码中__eq__和is_empty方法存在逻辑错误,可按需修正:

def is_empty(self)-> bool:
    '''Returns True if the sector has empty area, otherwise returns False.'''
    return self.fr >= self.to or self.rad <= 0

def __eq__(self, other: Sector)-> bool:
    '''Returns True this sector is the same as the other, otherwise False.'''
    return self.fr == other.fr and self.to == other.to and self.rad == other.rad

验证效果

按测试用例的赋值,s1的to属性应为70、半径大于等于30,调用s1.intersect(s2)得到的新Sector对象str()结果恰好为"60 70 30",匹配断言要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:06:04