CYBER WEEK - EXTRA SAVINGS EVENT
TRY A FREE LESSON

Breaking a loop issue

My Code:

Steps = []
a,b = input().split(' ')
a,b = [int(a),int(b)]
while True:
    try :

        steps = 0
        if a % b == 0 :
          Steps += [0]

        else :
            while a % b != 0 :
                a = a + 1
                steps += 1
            Steps += [steps]

    except ValueError :
        pass

for i in Steps :
    print(i)   

well in this code I trie to solve this problem : Problem - 1328A - Codeforces
but the issue is that I didn’t found a way to stop the loop when the input is finished, If you took a look at the problem, you’ll find that the input is something like that :

5
10 4
13 9
100 13
123 456
92 46

and the output should be :

2
5
4
333
0

I can for example stop the loop, by using break() if a is divisible by b, but this is not correct for every case…
All in all, I need a way to stop the loop just after the input is finished.

Good question. And this leads to learning about a programming concept (sort of) of using a flag variable (I have usually only seen them being referred to as “flags” in the context of their use, but what they are used for is more important than the terminology itself)

a = 10
loop_status = True

while loop_status:
    a += 10
    print(a)
    if a == 100:
        loop_status = False

The loop_status variable is essentially being used as a flag to signal your code if some condition is being met or something is changing.

Try to understand and then run the above code to see what happens. Then apply it to your code accordingly.

1 Like

yes in this way I can stop the loop if a condition is met, but I want to stop it whenever the user input stops, so for example if the user give me 5 inputs then he pressed enter then I should return the answer and the same for n inputs…

This can depend on how the input is being provided. Usually, platforms, like the one you link, provide code that handles this for the user.

There are different ways to do this. So, the following may or may not work for you.

numbers = []
c = input()
flag = True
while flag:
    for _ in range(int(c)):
        a, b = input().split()
        numbers.append((int(a), int(b)))
    flag = False
    
print(numbers)
  • You take the first number as your first input in c. In the data you provided above, that would be 5.
  • You then create a while loop which keeps running till the user is inputting something. This could vary, as I said, depending on how the input is being accepted (sometimes there isn’t a terminal input option, or it’s being accepted through a text file etc.)
    • Inside the loop, you have a for loop that runs based on c.
    • Once the for loop is done running, you change the flag

There are other approaches as well. I would recommend also searching online for something like “python multiline user input” and you should get some good stackoverflow answers you could try out.

1 Like

Thanks for this question as it gave me a little “Saturday morning challenge” that I just couldn’t resist! Although it’s not the most elegant and could probably be tweaked for edge cases, I came up with a solution that works well enough.

My Solution
num_inputs = int(input())
solutions = []

for _ in range(num_inputs):
    steps = 0
    try:
        a, b = input().split(' ')
        a, b = int(a), int(b)
    except ValueError:
        print("Not a valid input. Please provide two and only two integers.")
        break
    
    loop_status = True

    while loop_status:
        if a % b == 0 :
            solutions.append(steps)
            loop_status = False
        else :
            a += 1
            steps += 1

for solution in solutions:
    print(solution)
1 Like

First, you are welcome !
Second, yes your code seems to be working but it doesn’t solve my problem, which is stopping the loop without putting a condition, just after finishing all the input and pressing enter the answer should be printed, e.g. I shouldn’t specify the number of inputs in the start. And also there is another problem which has to do with the break when just one integer is provided, actually it should just ignore it, not breaking.

Thank you for you time.

1 Like

I’m not sure I understand how we could possibly do this…because if we don’t specify the number of inputs at the start, how can our program determine when the user has finished inputting an arbitrary number of value pairs? :thinking:

For example, can we now when the user tape enter in the keyboard then waited some amount of time without typing anything else, and therefore breaking the loop using an if statement ?

Perhaps this will do what you want? Seems overly complicated to me and I’m skeptical that the original problem is asking for such an implementation…

From the instructions, it appears that the first line of input is supposed to be the number of inputs:

Input
The first line of the input contains one integer t (1≤ t ≤10^4) — the number of test cases. Then t test cases follow.

Best of luck!

1 Like

oh thank you, I misread the problem. But, now this solution seems to work, but do you have any advise to have less amount of time while executing the algorithm ( time complexity), because it fails on one of the tests…

this is my code :


Steps = []
number_of_inputs = int(input())
for _ in range(number_of_inputs):
        try:
            a, b = input().split()
            a, b = [int(a), int(b)]

            steps = 0
            if a % b == 0:
                Steps += [0]
            else:
                while a % b != 0:
                    a = a + 1
                    steps += 1
                Steps += [steps]

        except ValueError:
                pass
for i in Steps:
    print(i)


Hi, @issamelimrany.

But for algorithmic complexity you should not use the while loop at all. You need the number of steps mathematically.

Steps = []
number_of_inputs = int(input())
for _ in range(number_of_inputs):
    try:
        a, b = input().split()
        a, b = int(a), int(b)
        if a % b == 0:
            steps = 0
        else:
            steps = (a // b + 1) * b - a
        Steps += [steps]
    except ValueError:
        print("Not a valid input. Please provide two and only two integers.")
        break
for i in Steps:
    print(i)

Thank you!

please, can you explain how you turned the while loop into this mathematical expression ?

You need to find the next number that will be divisible without a remainder by the known divisor. This is a backward solution. To find this number we need to get the second divisor.

So we integerically divide a by b and get a number that is 1 less than our divisor. Then we raise it by 1 and multiply it by b. So we get the next number in the series without using While. And subtracting the initial number “a” from it, we get the number of steps.

Here’s an example

5 и 2

The operation 5 / 2 will give 2.5 respectively the next number to be divided by an integer should give 3. We need to go from 2.5 to 3 ourselves. But instead of rounding up, we can make it easier.

do the operation 5 // 2 which will give us 2. Make 2 + 1 and get 3. After that we have to go back to our basic number series 3 * 2 to get 6.

The final touch is to calculate the steps 6 -5 = 1 step.