I am trying to figure this problem out but I can't seem to get the code right. Please help.


OUESTION:

Implement a subclass of list called myList. It will behave just like the list class except for iteration:

Usage:
>>> l = myList([3,5,7,9])
>>> for item in l:
print(item)

3
8
15
24

Explanation: the iteration is actually over all the partial sums of list l:

* 3,
* 3+5,
* 3+5+7, and
* 3+5+7+9.

MY CODE:

class myList(list):
    def __iter__(self):
        return ListIterator(self)

class ListIterator(object):
    def __init__(self, lst):
        self.lst = lst
        self.index = 0
    def __add__(self, ):
        if self.index >= len(self.lst):
            raise StopIteration
        res = self.lst[self.index]
        self.index += 2
        return res

I'll give you two hints:

  1. You need a constructor. Use this:
    class myList(list):
      def __init__(self,*args):
       super(myList,self).__init__(args)
  2. Your __iter__ method can use a similar technique, but beware infinite recursion if you try to iterate over myList in that method. I used the yield keyword in my implementation

I created a solution in 8 ilnes (I showed you 3 of them). Then I exercised it as follows:

l = myList(1)
l.append(3)
l.extend([5,7,9])
print l

for p in l:
  print p
print l # prove I didn't change the list
"""output:
[1, 3, 5, 7, 9]
1
4
9
16
25
[1, 3, 5, 7, 9]
"""

By the way: The mathemaniac loves that the sum from 1 of all the odd numbers is always a square.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.