【发布时间】:2020-01-14 22:48:48
【问题描述】:
我正在做 leetcode,我的代码给了我这个我无法理解的错误。我被要求反转整数,这很简单。这些是测试用例:
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
我认为我需要的只是 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
但是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
【问题讨论】:
-
先检查
if lst:,看看列表是否不为空。或者两者都if lst and lst[-1] == '-': -
请输入触发该条件的输入。您可能在处理字符串 0 吗?
标签: python index-error