-2

I'm doing some Homework and the question is: Write a Python Generator that walks through the nodes of a linked list.

Hint: Use yield.

class Node:
      pass

def my_generator():

start = Node()
point = start

point.data = 1
print(point.data)
point.next = Node()
point = point.next

point.data = 2
print(point.data)
point.next = Node()
point = point.next

point.data = 3
print(point.data)
point.next = Node()
point = point.next

point.data = 4
print(point.data)
point.next = None

I'm relatively new to Python, and I've spent the last 2 days trying to figure out how to use Yield in this piece of code.I understand I could do this way easier by using other options in Python but this is the set question for my homework. Thank you

Antnog
  • 3
  • 3
  • You might want to reformat your code. The whitespace got lost in the copy-paste, so it's unclear what your code does. – pzp Oct 11 '15 at 14:44
  • Thanks, just edited it now. – Antnog Oct 11 '15 at 14:47
  • First, your class won't run. The pass needs to be indented. The code that follows seems to just be creating a linked list 1 -> 2 -> 3 ->4 -> None, but your question seems to ask how to write code that would walk through a linked list, not create one. – joel goldstick Oct 11 '15 at 14:49
  • First of all it does run. Secondly, that's exactly what my code is supposed to do, creating a linked list that goes 1>2>3>4. – Antnog Oct 11 '15 at 14:54

2 Answers2

2

Taking a look at the basic shape of a generator might help:

def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

which we can just call and use in something taking an iterable, for example,

sum(firstn(50))

Your list seems to give me next and returns None when it's done, so you need

def my_generator():
    item = start
    while item is not None:
        yield num
        item = item.next

Decide if this is being a class member or not - I'll leave that up to you. I also haven't added code for the list itself.
Your current "generator" appears to be setting the data as it walks through - try to keep one function to populate the list, so you can make the generator just do one thing - walk the list.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
0

You should be using yield to generate an iterator of your list:

What does the "yield" keyword do in Python?

Community
  • 1
  • 1
lilezek
  • 6,976
  • 1
  • 27
  • 45