Can not concatenate 'str' and 'int' objects, but can I run it correctly through my IDLE?

advertisements

I'm running on 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 run without a hitch but running it on Code Eval on Python 2.7.3 It keeps returning a

cannot concatenate 'str' and 'int' objects

On the last line but I can't figure out why it's returning that as both parts seem to be an int.


I am not sure where this is working, but clearly orig_number is not an int . When you read stuff from a file , and then do strip() / splitlines() on it, you get back a list of strings.

Hence, in the for loop, test is a string, and hence orig_number is also a string.

You do not need to convert them to str explicitly and you should convert the orig_number to int before trying to add, and then convert them back to str to save in orig_number. Example:

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]))