Select higher value from a list // Python

Asked

Viewed 3,175 times

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 solution, I have tried using while, if and max(), but none of these are working.

With max() for example, my code is like this:

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

print list1 // I write the list on the screen

answer = max(list 1) // calculating the maximum value of the list

print reply // I write the answer on the screen

client.send(reply) // send the reply to the 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

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

Wrong, try it again. //server response stating that the entered value is not correct

Does anyone know what I’m doing wrong? or if there’s any other solution to writing this code?

Thanks in advance, hugs.

1 answer

1

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

I tested this through 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 function split I separated the received string into each character , and then using the function strip I removed the clasps.

Running the program, I received the following reply:

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

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

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
  • It worked, thank you very much!!!

Browser other questions tagged

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