ValueError: invalid literal for int() with base 10: '' *Codewars

ValueError: invalid literal for int() with base 10: '' *Codewars

我正在尝试解决有关 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)

而且我写了代码:

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]

它通过了所有测试,但出现错误:

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

我不明白为什么代码会引发此错误。谢谢

只有当 arr 为空时,您报告的异常才有意义。这是一个“无效”的输入,但这并不意味着它不会给你,只是你不希望给出正常的响应(你需要 return None)。

我建议在您的函数顶部添加一个检查:

if not arr:     # empty list
    return None

试试这个:

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

如果需要,您还可以在开头添加 Blckknght 的答案中的 if 语句。