Repeat Structures in Python

Asked

Viewed 154 times

-4

recently started my studies in programming and was doing a URI exercise in which I have to read an undetermined set of values M and N, where for each pair read, show the sequence of the smallest to the largest and the sum of consecutive integers between them (including N and M). Thinking on what the best way to solve me arose the following doubt, is it possible to make a loop of repetition within a Conditional Structure? Because I can solve this problem in a simpler way, but following a logic similar to repetition structures I can not at all present the correct result. Follow the link of the question: https://www.urionlinejudge.com.br/judge/pt/problems/view/1101

 M = int(input(""))
 N = int(input(""))

 soma = 0

 while True:
    if (M <= 0 or N <= 0):
       break

  if (M >= N):
     for N in range(N, M, 1):
        print(N)
        soma = soma + N
  else:
    for M in range(M, N, 1):
        print(M)
        soma = soma + M

print(soma)

M = int(input(""))
N = int(input(""))
  • Edit your question and paste the link of the question. Then we can read the statement and help you better.

2 answers

2

First detail is that the values of M and N will be read in the same input, not separately.

limits = input()
M, N = map(int, limits.split())

You can always build your loop from M to N, but if M is larger, invert the values:

if M > N:
  M, N = N, M

Code would look like this:

while True:
    limites = input()
    M, N = map(int, limites.split())

    if M <= 0 or N <= 0:
        break
    
    if M > N:
        M, N = N, M

    soma = 0
    for numero in range(M, N+1):
        print(numero, end=' ')
        soma += numero
    print(f'Sum={soma}')

You can simplify even more if you wish, but this I leave as homework for you.

0

Another way to resolve this issue is:

# uri 1101
while True:
    M, N = list(map(int, input().split()))

    if M <= 0 or N <= 0:
        break
    else:
        menor = min(M, N)
        maior = max(M, N)

        soma = 0
        for c in range(menor, maior + 1):
            soma += c
            print(c, end=' ')
        print(f'Sum={soma}')

Note that when we run this code the program screen gets dark with the cursor flashing in the upper left corner. At this time we must enter the values M and N, in same line, separated for a single space and press enter.

From now on the algorithm will perform all tasks and display the results.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.