简体   繁体   中英

Why is this always returning False?

Why is this always returning "box1 won't fit in box2" . def canBox1FitInBox2 always returns false even if it's not... What am I missing?

Even if the input is box1 = 1,1,1 and box2 = 10,10,10 .

This is an exercise, I know there are probably a lot of better ways to do this but I need it to be done like this:

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 I Wrote)\
    # 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
        # TODO: Finish this method (^This I Wrote)\

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])

(This I Wrote)\
def canBox1FitInBox2(box1, box2):
    if box1.getLongestSide() <= box2.getShortestSide():
         return canBox1FitInBox2 == True
    else:
         return canBox1FitInBox2 == False
(This I Wrote)\
#TODO: Use the getLongestSide and getShortestSide methods in the Box Class to determine
if box1 will fit in box2 then return true or false.

#Hint: if the longest dimension of box1 is smaller than the shortest dimension of
box2, then box1 fits in box2


if canBox1FitInBox2(box1, box2) == True:
    print("box1 will fit in box2")
else:
    print("box1 wont fit in box2")

In your code, the function canBox1FitInBox2 is returning values after comparing the function called again canBox1FitInBox2 without arguments, with True and False using the comparison operator(==)

Thus, calling the function without argument is throwing some garbage value and it is being compared with True and False, and thus function is returning always False.

Simply do this:

if box1.getLongestSide() <= box2.getShortestSide():
     return True
else:
     return False

and your code will run fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM