Python URI error - 2588 - Palindromes

Asked

Viewed 319 times

-1

By going up my code to URI Online Judge (problem 2588), makes a mistake, and I’m not getting it right at all.

The statement is this: enunciado

And my code sent was this:

entrada = input()

letras_unicas = set([i for i in set(list(entrada)) 

if entrada.count(i) %2 != 0])

if len(letras_unicas) > 1:
   print(len(letras_unicas)-1)
else:
   print(0)

And the error presented:

erro de compilação

  • The way you provided the code is unclear as it is, but if you are getting indentation error on a specific line and you believe the line is ok, possibly the error is directly on the line above. Can you run this code in your local environment? If you haven’t done this test before, add it to your script: if __name__ == '__main__': sua_funcao()

2 answers

3


You broke the line where you shouldn’t, inside the set(...).I think the way you wanted it was this:

entrada = input()

letras_unicas = set([i for i in set(list(entrada)) if entrada.count(i) %2 != 0])

if len(letras_unicas) > 1:
   print(len(letras_unicas)-1)
else:
   print(0)

However, this code still does not work completely. Because it is only looking at the first line of the input. If the first line is batata, he’ll find a way out 1. If it is aabb, will give 0. If it is abc, will give 2. These are the expected results.

See here this running on the ideone.

To finish the exercise, I think the only thing you’ll need to do is put a loop to read several lines from the file. Each time the input() is executed, a line is read, so a while True: to read all lines. Use a try with a except EOFError and a break as a stop condition to exit the loop.

The code would then look like this:

while True:
   try:
      entrada = input()
   except EOFError:
      break

   letras_unicas = set([i for i in set(list(entrada)) if entrada.count(i) %2 != 0])

   if len(letras_unicas) > 1:
      print(len(letras_unicas)-1)
   else:
      print(0)

See here this running on the ideone.

  • Got it Victor, I really appreciate the help! How would I implement this Loop ? Or how would I present the result later, you know?! Could you enlighten me a little bit .. ?

  • @Flávia Resposta editada.

0

To resolve this issue you can implement the following code below...

import sys


def main():
    for line in sys.stdin:
        oc = [0] * 26
        for char in line[:-1]:
            oc[ord(char) - ord('a')] += 1
        ans = 0
        chance = True
        for cnt in oc:
            if cnt % 2 == 1:
                if chance:
                    chance = False
                else:
                    ans += 1
        print(ans)


main()

See here the functioning of the algorithm.

This algorithm has already been testado, submetido and properly aprovado on the website Uri, under programming language Python 3.

Browser other questions tagged

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