python vector input

Asked

Viewed 2,057 times

1

I have some input values of a matrix that will have the input of the following form:

1 2 3 4

2 3 4 0

so I’m trying to take the first line of m+n elements to turn everything into float, but it’s not working.

aux = [0]*(m+n)

for i in range(m):
    aux = input()
    print(aux)
    aux = aux.split( )
    print(aux)
    map(float, aux)    

print(aux[1])
  • It was not very clear what you need to do. You can try to explain better?

  • I have to make a simplex and I will have several entries and a matrix A, this matrix would have a bit n of columns and m of rows. the input will be 1 2 3 4, for example. I need to transform this to float. It seems to me that when you enter a line like this in input() it takes like a string.

2 answers

1


I managed to solve the problem. But I realized that my problem was to receive the answer from map

m = int(input())
n = int(input())

A = []
for i in range(m):
    A.append( [0] *(m+n))

list = [0]*(n)
new_list = []
List_copy = [0]*(m*n)

for i in range(m):
    lista = input()
    #print(lista)
    lista = lista.split(' ')

    for item in lista:
        new_list.append(float(item))
        #print(new_list)

numpyList = np.asarray(new_list)
A = np.reshape(numpyList, (m,n))
print(A)

1

Okay, I think I understand what you need, so I’m going to really focus on the problem: a loop of repetition that reads m lines in the format a b c d ..., Separate this line into values and convert them to float, keeping such values in a list. For this we do:

m = int(input("Quantas linhas? "))
n = int(input("Quantas colunas? "))

for i in range(m):
    while True:
        row = input()
        values = row.split(' ')

        if len(values) == n:
            break

    values = list(map(float, values))

    print(values)

The for is to ensure that the m lines. THE while ensures that the input will always read the expected number of columns, thus preventing the user to enter a different value - if the matrix has 3 columns, the input 1 2 will be invalid. Read input, separate values with split in white spaces and converted to float with the function map.

That is, your code was on the right track, but must have been wrapped up with the returns of the function, remembering to assign the return to a variable. It is worth remembering that the return of map is a generator, so I used list to convert it to a list.

Browser other questions tagged

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