r/pythonhelp • • Jan 05 '21

Help with exercise

While studying for a finals exam for a beginners class on python, I stumbled upon the following exercise, which I cannot even begin to try to solve. It doesn't look like anything I have done before and it most definitely is not something my professor showed in class yet I would really appreciate any help as to how a solution might look for something like this.

So:If x = [1, 3.5, 4, 6.352, 10.143, 192, 212.25, 23.4] and y = [3.5, 2.65, 5.458, 8.644, 321.3, 34, 2.45], write code using "for" or "while" in python which will print pairs of x and y values, one pair in each line. The code must align the numbers on a 6-spot field , each number must show 2 decimal digits and the numbers must have a gap between them, so the end result should look like this :

(I'm sorry if something is not clear, I tried to translate everything as best I could)

5 Upvotes

5 comments sorted by

View all comments

3

u/sigh_in_silence Jan 06 '21

Cool problem! I'm going to make a couple assumptions, mostly that it's okay for these to print as strings to console. Probably there's a simpler way, but here's what I'd do.

For index in range(len(x)):

  1. (Assuming these are lists of ints) Use a precision setting method to get x[index] to 2 decimal places (https://www.geeksforgeeks.org/precision-handling-python/)

  2. Now cast x[index] to a string

  3. Add sufficient spaces to the x[index] to get it to a length of 6

    1. spaces = 6 - len(x)

    2. x = " " * spaces + x (can prob make these two a one liner, just trying to make the logic clear)

  4. Replicate steps 1-3 for y[index]

  5. print x[index] + " " + y[index]

1

u/grumpymolerat Jan 06 '21

Thank you very much for the reply, I think I will be able to solve it now!