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

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!

1

u/grumpymolerat Jan 06 '21
x = [1, 3.5, 4, 6.352, 10.143, 192, 212.25, 23.4]
y = [3.5, 2.65, 5.458, 8.644, 321.3, 34, 2.45]
n = len(x)
for i in range(n):
    listx = x[i]
    listy = y[i]
    print("{:6.2f} {:6.2f}".format(listx, listy))
    if (i>=5):
        break

This is it finished, I finally did it, again, thank you very much for your help, even though I think I didn't follow your instructions to the letter per say...:P

2

u/sigh_in_silence Jan 07 '21

Oh nice! I never use .format so I didn't think of this, this is great. One thing though, you could simplify it a bit, at least from what I can tell.

If you only want to print the first 6, then you could do for i in range(5) instead of taking the length n and doing the if statement with the break.

And this is totally optional, but you could just use x[i] and y[i] in the print statement .format itself instead of creating new variables listx and listy for them.

1

u/grumpymolerat Jan 08 '21

You are absolutely right, truth is I thought I had to create the new variables because I didn't know x[i] and y[i] worked like that. And, just a small correction, to print the first 6 I have to do for i in range(6), not 5, but otherwise you were right again.