I would like to know what I might be doing wrong in trying to find the number of nodes connected in a loop. Here is my implementation in python.
# Defined Node class
class Node(object):
data = 0
def __init__(self, data=None, next_node=None):
self.data = self.increment()
self.next = next_node
def increment(self):
Node.data += 1
return Node.data
def setNext(self, next_node = None):
self.next = next_node
I defined a function to create a node chain by taking on an arbitrary number of nodes and also a desirable loop length as parameters.
def create_chain(num_of_nodes, loop_size):
nodes = [Node() for _ in range(num_of_nodes)]
if loop_size == 0:
return nodes[0]
else:
for node, next_node in zip(nodes, nodes[1:]):
node.next = next_node
# cleaned_nodes.append(node)
nodes[num_of_nodes-1].next = nodes[(num_of_nodes - loop_size)-1]
return nodes[0]
I then defined a function to determine the size of a loop given the initial node which passed as a parameter to the function.
def loop_size(node):
count = 0
if node == None:
return 1
if node.next == None:
return 1
slow = fast = node
while(slow or fast or node.next):
count += 1
if fast.next == None:
#count += 1
break
if slow == fast.next or slow == fast.next.next:
count += 1
break
slow = slow.next
fast = fast.next.next
return count
I wrote a few tests but this particular assertion did not work, and I'd like to understand why.
def test_very_long_chain(self):
self.chain = create_chain(3904, 1087)
self.assertEqual(loop_size(self.chain), 10, 'Loop size of 10 expected')
I get this assertion error;
AssertionError: 3264 != 10 : Loop size of 10 expected
I'd really appreciate some guidance on this. Thanks