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