0

I have two classes - Item and AIShoppingCart (which has dictionary, for example {"milk" : Item(2, 2.28, 1)}). I have to find the most likable item from my cart using reduce and I am not allowed to use max(). Unfortunately, my program throws an error

<lambda>() takes 1 positional argument but 2 were given


class Item:
def __init__(self,quantity,price,likable):
    self.quantity = quantity
    self.price = price
    self.likable = likable

class AIShoppingCart(ShoppingCart):
def __init__(self,items):
    super().__init__(items)
def add_item(self,name,quantity,price):
    if name in self.items:
        self.items[name].likable+=1
        self.items[name].quantity+=quantity
    else:
        items[name]=Item(quantity,price,1)

def findMostLikable(self):
    return reduce(lambda x:self.items[x].likable>1, self.items)

How should I use reduce?

0

1 Answer 1

3

Please look up the documentation for reduce. If you do reduce(f, [a, b, c, d]) this will essentially be applied as f(f(f(a, b), c), d) -- so reduce essentially takes 2 elements at a time and reduces them to 1.

In your case the reduce function just has to pick the greater element by value:

return reduce(lambda a, b: a if a[1].likable >= b[1].likable else b,
              self.items.items())

The .items() function gets your dictionary's key-value pairs as a list of tuples, whose value I get using a[1]/b[1] -- the returned result is a key-value-tuple.

If you just want the maximum value, without caring about the keys:

return reduce(lambda a, b: a if a.likable >= b.likable else b,
              self.items.values()).likable
Sign up to request clarification or add additional context in comments.

4 Comments

I get it, but I cannot solve how to compare the items by the likable property.
That would be a[1].likable, I'll update my answer, sorry about that
I am getting the following error ('eggs', <Item.Item object at 0x000001EA58C43908>) But yes, it almost works. The output should be eggs's likable count.
That's not an error, that's the result. You can add [1].likable to the very end to get just the value, but in that case you can just iterate over the .values() directly. I'll update my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.