Python盒子适配判断函数canBox1FitInBox2始终返回False排查
问题现象
- 实现的
canBox1FitInBox2函数无论输入什么参数,始终返回False,固定输出box1 won't fit in box2 - 输入测试用例
box1 = 1,1,1、box2 = 10,10,10(明显满足适配条件)时依然返回错误结果 - 题目约束:必须基于给定代码框架实现,判断规则为box1的最长边小于等于box2的最短边时,box1可放入box2,且必须调用Box类的
getLongestSide和getShortestSide方法完成判断。
错误根因
canBox1FitInBox2函数的返回逻辑完全错误:
- 代码中
return canBox1FitInBox2 == True的逻辑是判断「当前函数对象本身是否等于布尔值True」,函数对象和布尔值是完全不同的类型,这个判断永远为False - 同理
return canBox1FitInBox2 == False也永远返回False,因此无论传入的盒子参数是什么,函数都只会返回False - 额外问题:你在代码中自行添加的
(This I Wrote)\标记属于Python无效语法,运行时会直接抛出语法错误,正式代码需要删除这类标记。
修正后代码
Box类文件(Box.py)
class Box: length = 0 width = 0 height = 0 # This method will check the length, width, & height # then it will output which dimension is the longest def getLongestSide(self): self.max = self.length if self.width > self.max: self.max = self.width if self.height > self.max: self.max = self.height return self.max # This method should output which dimension is the shortest def getShortestSide(self): self.min = self.length if self.width < self.min: self.min = self.width if self.height < self.min: self.min = self.height return self.min
主运行文件
from Box import Box box1 = Box() dimensions1 = input("Enter box1's dimensions ex. 1 2 3").split() box1.length = int(dimensions1[0]) box1.width = int(dimensions1[1]) box1.height = int(dimensions1[2]) box2 = Box() dimensions2 = input("Enter box2's dimensions ex. 1 2 3").split() box2.length = int(dimensions2[0]) box2.width = int(dimensions2[1]) box2.height = int(dimensions2[2]) def canBox1FitInBox2(box1, box2): # 直接返回条件判断的布尔结果即可,无需多余比较 return box1.getLongestSide() <= box2.getShortestSide() if canBox1FitInBox2(box1, box2): print("box1 will fit in box2") else: print("box1 wont fit in box2")
修正后测试1,1,1和10,10,10的用例会正常输出
box1 will fit in box2,符合题目要求。
内容的提问来源于stack exchange,提问作者Yoan
相关产品推荐
相关产品推荐

