时间:2021-06-20 08:50:58 | 栏目:Python代码 | 点击:次
在有些情况下,利用try…except来捕捉异常可以起到代替if…else的作用。
比如在判断一个链表是否存在环的leetcode题目中,初始代码是这样的
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
slow = head
fast = head.next
while(fast and slow!=fast):
slow = slow.next
if fast.next ==None:
return False
fast = fast.next.next
return fast !=None
在 while循环内部,fast指针每次向前走两步,这时候我们就要判断fast的next指针是否为None,不然对fast.next再调用next指针的时候就会报异常,这个异常出现也反过来说明链表不存在环,就可以return False。
所以可以把while代码放到一个try …except中,一旦出现异常就return。这是一个比较好的思路,在以后写代码的时候可以考虑替换某些if…else语句减少不必要的判断,也使得代码变的更简洁。
修改后的代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
slow = head
fast = head.next
try:
while(fast and slow!=fast):
slow = slow.next
fast = fast.next.next
return fast !=None
except:
return False