How to solve product scalar without using numpy library (python)

Asked

Viewed 33 times

-2

Hello, I’m trying to do this operation without using the Numpy library, which in itself is already a tragedy.

I get from the user two vectors of equal sizes, and need to do the scalar product operation between them. Remembering which scalar product is a. b = a1.B1 + a2.B2 .... + an.bn

I think there’s something missing that I don’t fully understand...

For example, if I put vector A as [1, 2, 3] and vector B as [3, 2, 1], the result of multiplication between them should vector C = [3, 4, 3]. But the way this code was written what I have is: [3, 2, 1, 6, 4, 2, 9, 6, 3] Since I’m not able to multiply the elements of the vectors, it doesn’t even make sense to try to add the elements of the vector C to get the final product. follows the code:

vetorA = []
vetorB = []

numA = int(input('Digite o tamanho do vetor do A: '))
while len(vetorA) < numA:
    vetorA.append(int(input('Digite um numero para preencher o vetor A: ')))

numB = int(input('Digite o tamanho do vetor do B: '))
while len(vetorB) < numB:
    vetorB.append(int(input('Digite um numero para preencher o vetor B: ')))

if len(vetorA) == len(vetorB):
    vetorC = []
    for itemA in vetorA:
        for itemB in vetorB:
            new = itemA * itemB
            vetorC.append(new)
    print(vetorC)
  • 1

    It is worth remembering that the suggested solutions (both below and in the duplicate suggested in the blue block above) only work if the lists have the same size, because zip ends as soon as the smallest of them ends. If you are processing lists of different sizes, you would have to use itertools.zip_longest

1 answer

-1

You can use a list comprehension:

vetorC = [elemA * elemB for elemA, elemB in zip(vetorA, vetorB)]

The function zip returns the elements of vetorA and vetorB in parallel for each iteration, then

list(zip([1, 2, 3, 4], [5, 6, 7, 8]))

returns

[(1, 5), (2, 6), (3, 7), (4, 8)]

The list comprehension creates a list by building an item for each iteration. In this case, the item to be built is the value elemA * elemB. In the documentation there is an explanation explaining and demonstrating the use of list understandings.

  • 1

    Boaa, I’ll test it here.

  • This zip I didn’t know yet...

  • Yes! You can consult your documentation here and see more similar functions.

  • It worked here! I’m just not sure if I understand this "elemA * elemB for elemA, elemB "

  • I edited my reply with a link explaining how it works.

  • 1

    Thank you, you helped a lot!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.