Select greater value from a list // Python

0

I have the following problem:

I need to create a program that reads a random list of positive and negative values, and returns the highest value. As a workaround, I've tried using while, if and max (), but none of these are working.

With the max () function for example, my code looks like this:

  

list1 = client.recv (2048) // I get the random server list

     

print list1 // write the list on the screen

     

response = max (list1) // calculating the maximum value of the list

     

print response // write response on screen

     

client.send (response) // send response to server

As a result, I'm getting the following:

  

[4367859, 9736628, -530197, -5556671, 8246498, 3478110, -8101840, 3049971, 9121277, -4665343] // random list that is generated by   server

     

] // "response" result, that is, value that was sent to the server

     

Err, try again. // Server response stating that the value entered is not correct

Does anyone know what I'm doing wrong? or do you have any other solution for writing this code?

Thank you in advance, hugs.

    
asked by anonymous 30.03.2018 / 19:52

1 answer

1

When you receive the information from the server with the recv() function, your data arrives in the format of a string.

I tested this using the code:

lista1 = "[4367859, 9736628, -530197, -5556671, 8246498, 3478110, -8101840, 3049971, 9121277, -4665343]"
print lista1

resposta = max(lista1)
print resposta

To solve this, I used:

resposta = lista1.split(",")
for i in range(0,len(resposta)):
    resposta[i] = resposta[i].strip("[")
    resposta[i] = resposta[i].strip("]")

Using the split function, I separated the received string into each character , and then using the strip function I removed the brackets.

Running the program, I received the following response:

['4367859', ' 9736628', ' -530197', ' -5556671', ' 8246498', ' 3478110', ' -8101840', ' 3049971', ' 9121277', ' -4665343'] 

showing that the object is now a list and thus allowing you to use the max() function.

Using your code, the solution to your problem would be:

lista1 = client.recv(2048) // recebo a lista aleatória do servidor

lista1 = lista1.split(",")
for i in range(0,len(resposta)):
    resposta[i] = resposta[i].strip("[")
    resposta[i] = resposta[i].strip("]")

print lista1 // escrevo a lista na tela

resposta = max(lista1) // calculando o valor máximo da lista

print resposta // escrevo a resposta na tela

client.send(resposta) // envio a resposta para o servidor
    
30.03.2018 / 20:47