How to solve the "Exceeded Time Limit" in this code?

Asked

Viewed 150 times

0

Input format :

The input consists of a series of pairs of integers i and j, a pair of integers per line. All integers will be less than 1,000,000 and greater than 0.

Note that the entry only ends when there are no more numbers. Find out how to make your program work in this case. Each language has a different way of reading while there is still input to read.

Output format:

For each pair of integers i and j, print i and j in the same order in which they appear in the input and then print the maximum "cycle size" found. These 3 numbers must be separated by a space, with all 3 numbers in a row and being an output line for each line of the input.

def sequencia_de_collatz(i):
    listanum = [i]
    if i < 1:
        return []
    while i > 1:
        if i % 2 == 0:
            i = i / 2
        else:
            i = 3 * i + 1
        listanum.append(i)
    return listanum


inteiro_i = inteiro_j = maior = 0
while True:
    try:
        inteiro_i, inteiro_j = map(int, input().split())
        if inteiro_i < inteiro_j:
            for n in range(inteiro_i, inteiro_j + 1):
                tamanho_do_ciclo = len(sequencia_de_collatz(n))
                if tamanho_do_ciclo > maior:
                    maior = tamanho_do_ciclo
            print(inteiro_i, inteiro_j, maior)
            maior = 0
        else:
            for n in range(inteiro_j, inteiro_i+1):
                tamanho_do_ciclo = len(sequencia_de_collatz(n))
                if tamanho_do_ciclo > maior:
                    maior = tamanho_do_ciclo
            print(inteiro_i, inteiro_j, maior)
            maior = 0
    except EOFError:
        break
  • Are you aware that the content inside Try will never fire correct exception? Soon will never fall into the break that will come out of while True

  • 1

    please identar the file correctly - identation in Python is not an optional to leave beautiful - as is what we have there is a syntax error.

  • @Fourzerofive the platform that the code will run will cause it to give an Eoferror, so this "except".

  • @jsbueno o o "tab" n indents here and when I give space the code becomes a text, so it was like this.

  • 1

    Fix the indentation - you edit the code in your normal editor, paste the formatted code here, and or use the {} or put the code between marks of three severe accents - ''' . You can’t answer a question if you can’t read the code. (in this case you would understand, but no one is obliged, it’s not?)

  • @jsbueno I think you’re right now .

Show 1 more comment
No answers

Browser other questions tagged

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