Read pairs of integer values using python tuples

Asked

Viewed 896 times

0

I am new here, as well as in Python. This question I am presenting to you, is related to a question of college work. I have tried in every way to resolve and could not. I am here out of desperation. Here is my last attempt. Right after the question, is what I have managed to do so far - only the letter A.

Make a program, containing subprograms, that reads pairs of integer values, x and y, until the pair of zeros is read. Suppose each of these pairs represents a point in two-dimensional space. Keep these points as a vector of tuples (x,y). After the entry of all valid points, except the pair of zeros, write in the standard output:

  1. The amount of valid points;
  2. The dot vector, writing one point per line;
  3. If there are any, which are the closest points to each other. If there is a tie, write one of them;
  4. If they exist, which are the two most distant points from each other. If there is a tie, write one of them;
  5. If available, what are the averages of the x and y coordinates.

Definition

The distance between two points (Xa,Ya) and (xB,Yb) is given by the square root of the sum of the square of the differences, (Xa-xB) and (Ya-Yb).

What I did:

qtdParesLidos = 0
linhaLida = input()  # faz a leitura da primeira linha
x = float(linhaLida.split()[0])
y = float(linhaLida.split()[1])

while x != 0 or y != 0:  # repete até que o ponto 0 0 seja lido
    qtdParesLidos = qtdParesLidos + 1
    linhaLida = input()  # faz a leitura da próxima linha
    x = float(linhaLida.split()[0])
    y = float(linhaLida.split()[1])
  • I couldn’t make sense of your doubt. You mention everywhere the whole numbers, but in the code you converted to floating point number/float? Your problem is just that question, so all the other 4 points of the work are irrelevant to your specific question?

1 answer

2


The code you wrote will work well to read the data, and stop the input. The input must be integer, but the outputs of some of the requested items are decimal, so there is no problem in using the float instead of int. Except that item 2 asks for the printing of the input coordinates, so it will be better to convert them to integers in the final job.

So, the points that it seems to me you need to understand to be able to do the whole exercise:

  1. A Python "tuple" is a sequence of values - which is usually declared straight into the code. It is different from "lists" because once created they can no longer be changed - it has a fixed value. They are created simply by placing the desired values separated by commas, and all this within parentheses (in some cases, parentheses are even optional - just separate values by comma that Python creates a tuple). Example: ponto = (x, y) or ponto = x, y are two lines that will create a tuple in which the first element will have the value that is x and the second the value that is y. To recover the element just use ponto[0] (or 1 in square brackets for the other element). Lists and tuples function as "sequences" - and the number inside the bracket is the position of the desired element.
  2. "Lists": are another type of Python sequence. Unlike the "tuples" can have their elements and their length changed after they are created. One of the most used methods is the .append - it inserts a new element at the end of the sequence. Ex:

--

coordenadas = []  # cria uma lista vazia
coordenadas.append(ponto)  # acrecenta o valor referenciado na variável "ponto" à lista. 

The best way to understand lists is to enter the interactive Python prompt and play a little - check its content, add elements with the methods append(element) and Insert(position, element). See how you can retrieve elements at specific positions using brackets. The full documentation is here: https://docs.python.org/3/tutorial/datastructures.html

Question that if you know how to answer you will see that you are on the right track: if each element of the list is a tuple with two coordinates, how do I recover the "x coordinate" of the element at position 0 of the list? Sounds hard? - but let’s go in parts - let’s assume I have the following code snippet:

x = 3
y = 4
ponto = (x, y)
coords = []
coords.append(ponto)

What will appear on the screen if I digest coords[0]? And if I type ponto[0] ? (in doubt, type the above in the interactive Python prompt until you have no doubts). And what happens if I continue this sequence of commands and type:

consulta = coords[0]
x1 = consulta[0]

What will be the value in x1? Do I need the intermediate variable "query"? Or can I write directly coords[0][0] (try at the interactive prompt)

  1. you also need to know that there is built-in function len that always returns the length of a sequence . Ex: len(coords).
  2. Remember that the command for in Python, unlike the for in other languages always runs through a sequence - the body of the for is executed once for each elementof a sequence. Ex.:

--

for elemento in coords:
       print("A coordenada x nesse elemento é", elemento[0])

The items 3 and 4 of the exercise are the most complicated even, and those that require some programming logic. I hope the concepts I described above help you to understand well what you need until this part. To do the 3 you will need:

  1. of a variable to store the closest items ever found - remember that the variable can be a tuple or a list, so the two dots you’ll need to "remember" in the answer can be in the same variable
  2. a variable to store which was the shortest distance ever found between two points. Initialize it with a large value;
  3. a "for" to traverse all points - inside it another "for" to traverse all points again. In the body of that second "for" you: check if the points of the first is and the second are the same. If they are, continue (see command continue: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-Else-clauses-on-loops ). Calculate the distance between the selected point in the first is and the second - if it is less than the lowest value you have ever seen, save these two points, and the value of the distance found. At the end of the two "for", the variable with the dots will have the result that Voce needs to print.

Calculating the greatest distance between two points should be quiet - is almost the same thing, just use logic appropriately.

The average: just have variables to add up all the values of x, all the values of y, and divide that by the total of points (which you already know how to calculate). Good - I hope that with this you have enough walk within the exercise

  • 1

    Gosh, thank you so much. It helped me a lot. I was already giving up the question. Have a good day.

Browser other questions tagged

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