Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the (multiplicative) product of a tuple or list?

Let's say I have a

class Rectangle(object):                                               
def __init__(self, length, width, height=0):                                                   
    self.l = length                                               
    self.w = width                                                
    self.h = height                                               
    if not self.h:                                                     
        self.a = self.l * self.w                                       
    else:                                                              
        from itertools import combinations                            
        args = [self.l, self.w, self.h]                                
        self.a = sum(x*y for x,y in combinations(args, 2)) * 2
                 # original code:
                 # (self.l * self.w * 2) + \                            
                 # (self.l * self.h * 2) + \                            
                 # (self.w * self.h * 2)                                
        self.v = self.l * self.w * self.h                                           

What's everyone's take on line 12?

self.a = sum(x*y for x,y in combinations(args, 2)) * 2 

I've heard that explicit list index references should be avoided.

Is there a function I can use that acts like sum(), but only for multiplication?

Thanks for the help everyone.

like image 651
yurisich Avatar asked Oct 22 '11 19:10

yurisich


People also ask

Can tuple be multiplied?

Concatenating and Multiplying Tuples Concatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple. The * operator can be used to multiply tuples.

What is the difference between tuple and list with example?

List and Tuple in Python are the classes of Python Data Structures. The list is dynamic, whereas the tuple has static characteristics. This means that lists can be modified whereas tuples cannot be modified, the tuple is faster than the list because of static in nature.

Can you hash a tuple Python?

The hash() function can work on some datatypes like int, float, string, tuples etc, but some types like lists are not hashable. As lists are mutable in nature, we cannot hash it. This hash value is used to map other values when we use dictionary.


1 Answers

In short, just use np.prod

import numpy as np
my_tuple = (2, 3, 10)
print(np.prod(my_tuple))  # 60

Which is in your use case

np.sum(np.prod(x) for x in combinations(args, 2))

np.prod can take both lists and tuple as a parameter. It returns the product you want.

like image 69
cwilmot Avatar answered Oct 11 '22 13:10

cwilmot