1

Problem Statement

Given an integer n, find two integers a and b such that,

#a >= 0 and b >= 0
#a + b = n
#DigitSum(a) + Digitsum(b) is maximum of all possibilities

def solve(n): 

    len_of_n = len(str(n))
    len_of_n-=1
    a = '9'
    a = (a*len_of_n)
    #print(a)
    b = (int(n) - int(a) )  # This is the line where it points to error.
    #print(b)

    digits_of_a = []
    digits_of_b = []
    for i in str(a)[::-1]:
         digits_of_a.append(int(i))   
    for i in str(b)[::-1]:
         digits_of_b.append(int(i))

    return (sum(digits_of_a) + sum(digits_of_b))

The code actually reports correct answers on test cases on 'attempts' on codewars.com but fails final submission. It exits with error code 1. It says ValueError: invalid literal for int() with base 10: ''

I have read this other thread on this and understand that error is due to trying to convert a space character to an integer. Can't figure why would that statement get space charater. Both of them are int representations of string...?

5
  • What are the values of n and a when it hits the error? It And what are you passing into the function? The most likely thing, I think, is that the string n is unable to be casted to an int, either because it's an empty string or because it has non-digit characters in it. Commented Nov 24, 2018 at 7:19
  • N is already an int why would you int(n) ? Commented Nov 24, 2018 at 7:24
  • Do you by any chance pas a single digit value? Commented Nov 24, 2018 at 7:28
  • n is an integar passed to the func. a is constructed on the fly based on total 'digits' in the n. Error suggests it's due to empty string. But I cannot figure why/how can I have empty string with valid int value n passed to the def. Commented Nov 24, 2018 at 7:29
  • @TobiasWilfert Had changed as part of trial and error.. Originally I just had (n - int(a)) I am not sure what values are passed by the test engine. The test cases on codewars shows all 8 assertions passed but then also shows this error. So it deems my code inadmissible. Snapshot below. Commented Nov 24, 2018 at 7:33

1 Answer 1

2

When you pass a single digit int to the function you get this error because len_of_n = len(str(n)) will be equal to 1 and len_of_n-=1 will be equal to 0. 0 * '9' will give you an empty string which can not be converted to an int. Thus giving you the error

invalid literal for int() with base 10: ' '

Sign up to request clarification or add additional context in comments.

2 Comments

Bingo! Makes sense. Let me edit and give one more go!
@JigishParikh you will probably need to make an extra case if n is only 1 digit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.