简体   繁体   中英

Problem breaking out of a generator while iterating through a for loop

Assigned to design a linked list class from scratch using a generator to iterate through the list, but I've had a problem debugging this issue:

class LinkedList:

    def __init__(self, data = None):
        self.node = Node(data)
        self.first = self.node 
        self.last = self.node
        self.n = 1

    def append(self, data = None):
        new = Node(data)
        self.last.next = new
        self.last = new
        self.n += 1

    def __iter__(self):
        self.index = self.first
        return self.generator()

    def generator(self):
        for i in range(0, self.n):
            yield self.index
            self.index = self.index.next

One of the tests that the current generator passes is:

for n in a:
    print n

# which should and does output

0
1
2

However, it fails to output the proper values in this case

for n in a:
    if n == 2:
        break
    else:
        print n

# Outputs 0 1 2, instead of:

0
1

I think my understanding of generators is lacking, and would love any help you guys have to offer!

  • Your shouldn't use n == 2 as the break-condition.

Try this:

# Assume your defined class `Node.py` like this:
class Node:
    def __init__(self, data=None):
        self.val = data
        self.next = None

# I didn't modify your `LinkedList.py`
class LinkedList:

    def __init__(self, data=None):
        self.node = Node(data)
        self.first = self.node
        self.last = self.node
        self.n = 1

    def append(self, data=None):
        new = Node(data)
        self.last.next = new
        self.last = new
        self.n += 1

    def __iter__(self):
        self.index = self.first
        return self.generator()

    def generator(self):
        for i in range(0, self.n):
            yield self.index
            self.index = self.index.next


if __name__ == '__main__':
    ass = LinkedList(0)
    ass.append(1)
    ass.append(2)
    ass.append(3)

    for n in ass:
        if n.val == 2:  # Notice here
            break
        else:
            print(n.val)  # And here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM