0

My code receives two lines of input and splits those into lists. The result should look like:

input

4 6
2 4

output

2.0 1.5

I'm very new to coding, so my code isn't the most efficient, but here it is:

U = list(input().split(" "))
I = list(input().split(" "))
for z in range(len(U)):
    for x in U[z]:
        for y in I[z]:
            R = float(x) / float(y)
            print(round(R, 1), end=" ")

When I remove for x in U[z]: it works perfectly fine, except it prints every possible result. It also works fine with integers without removing the z loop. The full code for floats, however, prints ValueError: could not convert string to float: '.'. Is there a way to fix this without messing with the code too much?

4
  • 3
    Which version of Python are you using? I just executed exactly that and the output is 2.0 1.5, no errors. The input I used was 4 6, then hit Enter, then 2 4 and Enter again Commented Nov 19, 2021 at 21:54
  • 1
    You don't need to call list(), split() always returns a list. Commented Nov 19, 2021 at 21:57
  • 1
    Just some small things. .split() returns a list, so there's no reason to use list() there. Also, you can replace the 3 for loops with one by using for x,y in zip(U,I):. Commented Nov 19, 2021 at 21:58
  • 1
    Please explain what you're trying to do. There are many possible solutions to fixing your code but you haven't provided any details about what the intended behavior is. Commented Nov 19, 2021 at 21:59

2 Answers 2

1

Your code works fine, but only for one digit number. As you iterate on each string value, 14 would generate '1' '4'


Just keep the outer iteration

for z in range(len(U)):
    print(round(float(U[z]) / float(I[z]), 1))

Or even better with zip

U = input(">>").split(" ")
I = input(">>").split(" ")
for x, y in zip(U, I):
    print(round(float(x) / float(y), 1))
Sign up to request clarification or add additional context in comments.

Comments

1

You shouldn't be looping over U[z] and I[z]. Those are strings, so you're iterating over the characters. And with nested loops, you're making a cross-product of all the characters in each list element.

Just use one loop over the indexes.

U = input().split(" ")
I = input().split(" ")
for z in range(len(U)):
    x = U[z]
    y = I[z]
    R = float(x) / float(y)
    print(round(R, 1), end=" ")

Or use zip() to loop over the two lists in parallel:

for x, y in zip(U, I):
    R = float(x) / float(y)
    print(round(R, 1), end=" ")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.