It is not possible to combine the objects 'str' and 'int', but can I run it through my own IDLE?

I am running Python 2.7.10 with the following code:

import sys

with open(sys.argv[1], 'r') as input:
    test_cases = input.read().strip().splitlines()

for test in test_cases:
    orig_number = test
    iteration = 0
    while True:
        if str(orig_number) == str(orig_number)[::-1]:
            print iteration, orig_number
            break
        iteration += 1
        orig_number = orig_number + int(str(orig_number)[::-1])

And it will work without failures, but run it on Code Eval in Python 2.7.3 It keeps returning

cannot concatenate 'str' and 'int' objects

On the last line, but I can’t understand why it returns this, since both parts seem int.

+4
source share
2 answers

I am not sure where this works, but it is clear that orig_numberit is not int. When you read material from a file and then do strip()/ splitlines()on it, you return a list of lines.

Therefore, in a loop for testis a string, and therefore is orig_numberalso a string.

str, orig_number int, , str orig_number. :

import sys

with open(sys.argv[1], 'r') as input:
    test_cases = input.read().strip().splitlines()

for orig_number in test_cases:
    iteration = 0
    while True:
        if orig_number == orig_number[::-1]:
            print iteration, orig_number
            break
        iteration += 1
        orig_number = str(int(orig_number) + int(orig_number[::-1]))
+4

test_cases, , str, int .

, , splitline pythonic- -:

import sys

with open(sys.argv[1], 'r') as input:
     for test in input:
            orig_number = test.strip()
            iteration = 0
            while True:
                if orig_number == orig_number[::-1]:
                    print iteration, orig_number
                    break
                iteration += 1
                orig_number = int(orig_number) + int(orig_number[::-1])

, string int , try-except.

try:
    orig_number = int(orig_number) + int(orig_number[::-1])
except ValueError:
    # raise exception or do stuff 
+2

Source: https://habr.com/ru/post/1609173/


All Articles