Jigish Parikh
Jigish Parikh

Reputation: 75

Python ValueError for code that calculates correct results

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...?

Upvotes: 1

Views: 77

Answers (1)

Tobias
Tobias

Reputation: 947

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: ' '

Upvotes: 2

Related Questions