forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhas_loop.py
More file actions
Latest commit
62 lines (51 loc) · 1.66 KB
/
Copy pathhas_loop.py
File metadata and controls
62 lines (51 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from __future__ importannotations
fromtypingimportAny
classContainsLoopError(Exception):
pass
classNode:
def__init__(self, data: Any) ->None:
self.data: Any=data
self.next_node: Node|None=None
def__iter__(self):
node=self
visited= []
whilenode:
ifnodeinvisited:
raiseContainsLoopError
visited.append(node)
yieldnode.data
node=node.next_node
@property
defhas_loop(self) ->bool:
"""
A loop is when the exact same Node appears more than once in a linked list.
>>> root_node = Node(1)
>>> root_node.next_node = Node(2)
>>> root_node.next_node.next_node = Node(3)
>>> root_node.next_node.next_node.next_node = Node(4)
>>> root_node.has_loop
False
>>> root_node.next_node.next_node.next_node = root_node.next_node
>>> root_node.has_loop
True
"""
try:
list(self)
returnFalse
exceptContainsLoopError:
returnTrue
if__name__=="__main__":
root_node=Node(1)
root_node.next_node=Node(2)
root_node.next_node.next_node=Node(3)
root_node.next_node.next_node.next_node=Node(4)
print(root_node.has_loop) # False
root_node.next_node.next_node.next_node=root_node.next_node
print(root_node.has_loop) # True
root_node=Node(5)
root_node.next_node=Node(6)
root_node.next_node.next_node=Node(5)
root_node.next_node.next_node.next_node=Node(6)
print(root_node.has_loop) # False
root_node=Node(1)
print(root_node.has_loop) # False