-1

So for the following code I have been trying to use singly linked lists in python to calculate the sum of a list based on the even numbers within that list. I've written the code for the linked list portion I believe but I'm stumped on how to get it to actually take the even numbers only and sum them. Right now my code looks something like this:

def createList(plist):
     linkedList = None
     # goes backwards, adding each element to the beginning
     # of the list.  
     for index in range(len(plist)-1, -1, -1):
        linkedList = insertValueHead(linkedList, plist[index])
    return linkedList

def sumEvens(linkedList): #This is what I'm looking for help with
    .... #code


def testSumEvens():
    myList = createList([14, 21, 29, 2, 16, 49, -26])
    print "The sum of the even numbers in the first list is ", sumEvens(myList)
    myList = createList([])
    print "The sum of the even numbers in an empty list is ", sumEvens(myList)
    myList = createList([5, 15, 25])
    print "The sume of the even numbers in the final list is ", sumEvens(myList)

How would I go about making this create a sum of these lists? Such as in the first, 14 + 2 + 16?

Johnathan Scott
  • 293
  • 1
  • 4
  • 20
  • 2
    make your list iterable by defining a `__next__` method ... then just use `sum` – Joran Beasley Aug 05 '14 at 19:20
  • 1
    Per [this question](http://stackoverflow.com/questions/13636640/python-checking-odd-even-numbers-and-changing-outputs-on-number-size) use ```num % 2 == 0``` to determine if the number is even or odd – wnnmaw Aug 05 '14 at 19:21
  • 1
    How does your list class look? Without knowing how it looks, I would suggest something along the lines of `((lst.head if lst.head % 2 == 0 else 0) + sumEvens(lst.tail)) if lst else 0` – tobias_k Aug 05 '14 at 19:21
  • 1
    Why are you writing your own implementation of `list`? Homework? – stderr Aug 05 '14 at 19:24
  • @stderr he's trying to learn linked lists for his own benefit, and he wants to start in Python before moving on to a language where it's actually useful, like C. He's asked five different questions on this implementation. – TheSoundDefense Aug 05 '14 at 19:31
  • See [here](http://stackoverflow.com/q/25131144/1639625) for how `insertValueHead` looks... those lists are nested dictionaries. – tobias_k Aug 05 '14 at 19:35
  • 2
    possible duplicate of [Using linked lists to sum only even numbers?](http://stackoverflow.com/questions/25134336/using-linked-lists-to-sum-only-even-numbers) – tobias_k Aug 05 '14 at 19:36

2 Answers2

0

As previously mentioned taking the modulous % of a number will yield the remainder. Thus if n%2 is 0, then the number is even. You could implement sumEvens like this...

def sumEvens(linkedList):
    runningSum = 0
    for number in linkedList:
        if number % 2 == 0:
            runningSum += number
            print number
    print runningSum

sumEvens([14, 21, 29, 2, 16, 49, -26]) # prints 6 (14+2+16-26)
The2ndSon
  • 307
  • 2
  • 7
  • 1
    ... assuming `linkedList` is just a regular Python list. – tobias_k Aug 05 '14 at 19:24
  • Correct or OP would have to modify his `linkedList` class to be an iterable http://stackoverflow.com/questions/9884132/understanding-pythons-iterator-iterable-and-iteration-protocols-what-exact – The2ndSon Aug 05 '14 at 19:27
  • 2
    @The2ndSon from what I can tell from his previous questions, he wants to implement it entirely C-style, only in Python instead of C. – TheSoundDefense Aug 05 '14 at 19:31
  • @TheSoundDefense, agreed. There was a very well constructed answer to a similar question by OP. It would be worth time to look at that again if you need help building your linked-list class http://stackoverflow.com/questions/25131144/using-single-linked-lists-how-to-swap-nodes-in-python – The2ndSon Aug 05 '14 at 19:35
  • @The2ndSon well the OP has not demonstrated thus far that he is reading the answers all that carefully, unfortunately. – TheSoundDefense Aug 05 '14 at 19:38
0

here is a very basic linked list example

class LLNode:
    def __init__(self,value):
        self.next = None
        self.val = value
    def __float__(self):
        return float(self.val)
    def __int__(self):
        return int(self.val)
    def __str__(self):
        return str(self.val)

class LL:
    head =None
    def iterNodes(self):
        tmp = self.head
        while tmp is not None:
            yield tmp
            tmp = tmp.next
    def iterInts(self):
        for node in self.iterNodes():
            try:
                yield int(node)
            except ValueError:
                pass
    def iterFloats(self):
        for node in self.iterNodes():
            try:
                yield float(node)
            except ValueError:
                pass
    def iterStrings(self):
        for node in self.iterNodes():
            yield str(node)

    def insert(self,value):
        nn = LLNode(value)
        if self.head is None:
           self.head = nn
        else:
            list(self.iterNodes())[-1].next = nn



l = LL()
l.insert(1)
l.insert(2)
l.insert(3)
l.insert(4)
l.insert(5)
l.insert(6)
print "Sum of Even:",sum([n for n in l.iterInts() if n%2 == 0])
print "Sum of Odd:", sum([n for n in l.iterInts() if n%2 != 0])

the iterFunctions are the ones of primary interest to you I think

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179