-2

I'm trying to solve an an exercise on Codewars:

Given an array of integers of any length, return an array that has 1 added to the value represented by the array.

  • the array can't be empty
  • only non-negative, single digit integers are allowed

Return nil (or your language's equivalent) for invalid inputs. Examples

For example the array [2, 3, 9] equals 239, adding one would return the array [2, 4, 0].

[4, 3, 2, 5] would return [4, 3, 2, 6]

test.assert_equals(up_array([2,3,9]), [2,4,0]) test.assert_equals(up_array([4,3,2,5]), [4,3,2,6]) test.assert_equals(up_array([1,-9]), None)

and I have written the code:

def up_array(arr):
    print(arr)
    strings = ''
    for integer in arr:
        if integer < 0 or integer >= 10:
            return None
        else:
            strings += str(integer)

    a_string = "".join(strings)
    ints = int(a_string) + 1
    to_string = str(ints)


    return [int(x) for x in to_string]

It passed all of the tests, but it raises an error:

Traceback (most recent call last):
  File "tests.py", line 15, in <module>
    test.assert_equals(up_array([]), None);
  File "/workspace/default/solution.py", line 11, in up_array
    ints = int(a_string) + 1
ValueError: invalid literal for int() with base 10: ''

I don't understand why the code raises this error. Thanks

JoshL1516
  • 117
  • 7
laikovski
  • 15
  • 6

2 Answers2

1

The exception you report makes sense only if arr is empty. That's an "invalid" input, but that doesn't mean it won't be given to you, only that you're not expected to give a normal response (you need to return None).

I suggest adding a check at the top of your function:

if not arr:     # empty list
    return None
Blckknght
  • 100,903
  • 11
  • 120
  • 169
0

Try this:

def up_array(arr):
    num = 1 + int(''.join(str(ele) for ele in arr))
    return [int(i) for i in str(num)]

print(up_array([2, 3, 9])) returns [2, 4, 0].

You can also add the if statement from Blckknght's answer at the beginning if you want.

Have a nice day
  • 1,007
  • 5
  • 11
  • If you need to pass tests based on our-of-range integers in the input (returning `None` instead of raising an exception), you would also need a check for those. – Blckknght May 05 '21 at 23:22
  • @Blckknght if you can control the input it's not *absolutely* necessary, but if it were me I still would. I just didn't include it in my answer, mainly because I wasn't worried about it. – Have a nice day May 05 '21 at 23:52
  • 1
    Sure, but if you could control the input, you'd not be having the issue the questioner was asking about. Proper handling of invalid input was the whole issue here, there's nothing else wrong with the rest of their code, even if it is less concise than yours. – Blckknght May 06 '21 at 01:05
  • @Blckknght I'd forgotten about what the problem was :P. Well, he did accept your answer, so no harm done. Thanks for keeping me on track ;). – Have a nice day May 06 '21 at 01:24