Search code examples
pythoninputuser-inputinfinite-loop

Loop depending on the number of inputs but I dont know the amount of inputs


I have this problem I want to solve: https://open.kattis.com/problems/doggopher.

The problem I have is that I don't understand how I am supposed to take the input if I don't know how many lines of gopher holes coordinates there will be. I want to make a loop that checks all the input coordinates and breaks the loop when a working hole is found but I don't understand how the program is supposed to know when I have put in all the coordinates. All the solutions I have found online claiming to be correct seem to just have an infinite loop whenever you only input one hole coordinate. Maybe I completely misunderstand the problem but I would like to get some clarification or guidance on how to solve that issue.

Edit* Here is the code I am using right now in Python:

import sys


def distanceSquared(x, y, a, b):
    return (x - a) ** 2 + (y - b) ** 2


gx, gy, dx, dy = map(float, sys.stdin.readline().split())
notFound = True

try:
    while True:
        x, y = map(float, sys.stdin.readline().split())
        temp = 4 * distanceSquared(gx, gy, x, y)
        if temp < distanceSquared(dx, dy, x, y):
            print('The gopher can escape through the hole at (%.3f,%.3f).' % (x, y))
            notFound = False
except EOFError:
    pass


if notFound:
    print("The gopher cannot escape")



Solution

  • You can try the following

    import sys
    
    def distanceSquared(x, y, a, b):
        return (x - a) ** 2 + (y - b) ** 2
    
    gx, gy, dx, dy = map(float, sys.stdin.readline().split())
    notFound = True
    
    for line in sys.stdin:
        x, y = map(float, line.split())
        temp = 4 * distanceSquared(gx, gy, x, y)
        if temp < distanceSquared(dx, dy, x, y):
            print('The gopher can escape through the hole at (%.3f,%.3f).' % (x, y))
            notFound = False
            break
    
    if notFound:
        print("The gopher cannot escape.")