Saturday, December 4, 2010

Re: List compare is there something better than a double loop?

On 3 déc, 04:42, Sector7B <joe.greenaw...@gmail.com> wrote:
> Hi, I probably have a common problem and maybe i'm not thinking about
> this correctly, but here it is.
>
> I'm building a store that has a product_list (class ProductList:
> store, name, description) that contains .products (class Product:
> name, description, price etc...)
>
> I also have a cart that is built out of (class CartItem: product,
> user, qty).
>
> when the store page loads with the products I want to acknowledge that
> the item being shown is in the cart.
>
> So when i get the cart i have a result of [cartitem,cartitem,cartitem]
> and i have a product_list of [product,product,product,...]
>
> So the simpleton in me wants to do a double loop (cart/product_list)
> and compare product == cartitem.product if so, do something.

Simplest solution that has a chance to scale- set lookups are O(1):

cart_products = set(cartitem.product for cartitem in cart)
for product in product_list:
if product in cart_products:
do_something()


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate