Hey everyone! I'm tackling an exercise involving the scalar product using two sets of coordinate lists: a = [(1, 2), (3, 4), (5, 6)] and b = [(7, 8), (9, 10), (11, 12)]. I initially thought my implementation using the function `def scalar_product(x, y): return [sum(sum(i * j for i, j in zip(m, n)) for m, n in zip(x, y))]` made sense. But now I'm questioning if that's how these calculations are actually done in real programming. Should I instead present it like so: `def scalar_product(x, y): return [sum(i * j for i, j in zip(m, n)) for m, n in zip(x, y)]`? What do you think?
4 Answers
Comprehensions can be tricky in this scenario. Sometimes being straightforward is better for clarity. But, if the goal is to practice comprehensions in linear algebra, I get why you’d want to tackle it this way! Just be cautious, as it can make the code harder to read for others.
Yeah, I think the exercise aims to teach you the flexibility of comprehensions. It’s useful in the long run!
I can see you're really diving into these concepts! Both of your implementation ideas are valid based on your goal. If you want the overall scalar product, go with the first. For element-wise products, stick with the second. Most of us use NumPy because it simplifies everything. Here's a quick example:
```
import numpy as np
a = np.array([(1, 2), (3, 4), (5, 6)])
b = np.array([(7, 8), (9, 10), (11, 12)])
scalar = np.dot(a.flatten(), b.flatten())
```
This gives you what you want without the hassle!
Honestly, in typical programming, you'd probably utilize a library like NumPy or PyTorch for these calculations. Pure Python isn't really how people handle these things day-to-day. But it's awesome that you’re engaging with it on a conceptual level!
Your first approach calculates what's known as the Frobenius inner product, treating 'a' and 'b' as matrices. The second option you gave computes pointwise, meaning it handles each corresponding pair from the lists separately. You might also consider treating 'a' and 'b' like lists of vectors, which gives a completely different 'scalar product'. It’s really about the context of how you're using these coordinates!
I see what you're saying, but I think it’s okay to use comprehensions in this case, as long as it’s clear. Your return statement isn't less readable than a long loop, and it likely performs better too!