trying to find loop nodes with iteration

Ok, so before you waste time, it was a fail.

But i still think it can be done...
I gotta walk away for a bit.  The things I looked up about iteration said it is faster on large data, and saves memory on large data...
So there was this codewars to figure out how to get to a loop point in a linked list, and find out the size of the loop, that's what I was trying to do...(faster then my original solution or solutions with while loops) but I'm missing something.  Anyhoo!   If your playing with these just remember if you make an infinite loop in the IterTool class, you may lock your computer up. 
Fair warning. 


class NodeX(object):
    def __init__(self, value, link):
        self.value = value
        self.link = link

class IterToolNode(object):
    def __init__(self, start):
        self.start = start
        self.stop = self.start.link
        self.count = 0
        self.final = 0
       

    def __iter__(self):
        return self

    def __next__(self):
        print("next")
       
        if self.stop == self.start or self.start.link == None:
            print('stopiter***********')
            print(self.count)
            raise StopIteration
        else:
            self.final = self.stop
            print("****")
            print(self.final.value)
            print(self.start.value)
            self.start = self.start.link
            self.stop = self.stop.link.link
           
            self.count += 1
               
            return self.count
           
# Setting up the looped list :
end = NodeX('end node', None)
snode = NodeX('start node', end)
loopn = NodeX('loop node', None)       
for x in range(0, 36):
    #print(end.value)
    if x != 10 and x != 35:
        NewNode = NodeX(x, None)
        end.link = NewNode
        end = NewNode
    elif x == 10:
        end.link = loopn
        end = loopn
    elif x == 35:
        Newnode = NodeX(x, loopn)
        end.link = Newnode
        end = Newnode
        print('x = 35')
        print(end, end.link.value)
    else:
        pass
       
# node test 1
"""
while snode and snode!= end:
    print(snode.link)
    snode = snode.link
    if snode == end:
        print('end node')
        print('end node value =', snode.value)
        print('end node.link.value = ', snode.link)
"""

nobb = IterToolNode(snode)

for x in nobb:
    pass
print("^^^^^")
print(nobb.count)
print(nobb.final.value)
       
   

       
   


So failure code:




Comments

Popular posts from this blog

playing with color in powershell python

JavaScript Ascii animation with while loops and console.log

playing with trigonometry sin in pygame