Insert the values of an N-size vector into the same Python line

Asked

Viewed 81 times

-1

Well, I made the following code, which is based on two vectors of size N that, multiplying the values of same Dice form a third vector resulting from this multiplication.

n = int(input(''))
vetor1 = []
vetor2 = []
resultante = []
for vet in range(n):
    if n >=1 and n <= 100:
        vetor1.append(int(input()))
for vet in range(n):
    if n >=1 and n <= 100:
        vetor2.append(int(input()))
resultante = [elemvetor1 * elemvetor2  for elemvetor1, elemvetor2 in zip(vetor1, vetor2)]
resultantef =' '.join(str(v) for v in resultante)
print(resultantef)

The problem arises from my input, since the N values of vector 1 need to be on a line and the N values of vector 2 need to be on a second line. Here is an example of the input for the output:

#entrada
5 #tamanho dos vetores 1 e 2
1 3 2 4 5 #valores do vetor1
6 8 9 7 6 #valores do vetor 2

#saída
6 24 18 28 30 #vetor3 resultante das multiplicações de mesmo indice entre vetor1 e vetor2

  • Does that answer your question? https://stackoverflow.com/questions/23253863/how-to-input-2-integers-in-one-line-in-python

  • @Vitorceolin I tested here as said in the question q you linked, it did not work.

2 answers

1

From what I understand, you want to implement a code that is able to assemble two vectors of the same size and a third vector, in which each of its elements is the product of the elements of the same indices of the two previous vectors.

For this you can use the following code:

n = int(input())
vetor1 = list()
vetor2 = list()
resultante = list()
for c in range(1, n + 1):
    v1 = int(input(f'Digite {c}º elemento do 1º vetor: '))
    v2 = int(input(f'Digite {c}º elemento do 2º vetor: '))
    v = (v1 * v2)
    vetor1.append(v1)
    vetor2.append(v2)
    resultante.append(v)

print(f'O primeiro vetor é: {vetor1}')
print(f'O segundo vetor é: {vetor2}')
print(f'O vetor resultante é: {resultante}')

Note that only one for is able to insert the values of each of the first two vectors and also of the resulting vector.

0

If what I understand is correct, you want to receive the values without having to use a repeat structure, you can use map + split and turn into a list:

n = int(input('Digite valor para N: '))

# os números devem ser digitados com um espaço entre eles, exemplo:
# 1 2 3 4
vetor1 = list(map(int, input('Digite os valores do vetor 1 separados por espaço: ').split()))
vetor2 = list(map(int, input('Digite os valores do vetor 2 separados por espaço: ').split()))

resultante = [elemvetor1 * elemvetor2  for elemvetor1, elemvetor2 in zip(vetor1, vetor2)]

print(f'Resultado final: {" ".join(str(v) for v in resultante)}')

Entree:

Digite valor para N: 5
Digite os valores do vetor 1 separados por espaço: 1 3 2 4 5
Digite os valores do vetor 2 separados por espaço: 6 8 9 7 6

Exit:

Resultado final: 6 24 18 28 30

Browser other questions tagged

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