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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With