Onu*_*bek 1 python index-error
我正在执行leetcode,我的代码给了我我无法理解的错误。我被要求反转整数,这很容易做到。这些是测试用例:
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Run Code Online (Sandbox Code Playgroud)
我发现我所需要的只是if语句来检查输入的条件,所以这就是我所做的:
class Solution:
def reverse(self, x: int) -> int:
string = str(x)
lst = list(string)
lst.reverse()
if((lst[0]) == '0'):
lst.pop(0)
if((lst[-1] == '-')):
lst.pop(-1)
lst.insert(0, '-')
output = ''.join(lst)
return output
Run Code Online (Sandbox Code Playgroud)
但是这一行if((lst[-1] == '-')):抛出一个IndexError: list index out of range错误。我正在做的是访问列表的最后一个元素。我不尝试访问不存在的索引。
我唯一需要知道的是为什么会发生此错误。因为这是leetcode,所以我想自己修复该代码。
最终密码
class Solution:
def reverse(self, x: int) -> int:
lst = list(str(x))
lst.reverse()
if(x < 0):
lst.pop(-1)
lst.insert(0, '-')
int_output = int(''.join(lst))
if(int_output < (2**32)):
return int_output
else:
return 0
Run Code Online (Sandbox Code Playgroud)