如何从链表中汇总数字?

时间:2014-08-05 19:16:49

标签: python linked-list

因此,对于以下代码,我一直尝试在python中使用单链表来计算基于该列表中偶数的列表总和。我已经编写了链接列表部分的代码我相信但是我很难理解如何让它实际只取偶数并加总它们。现在我的代码看起来像这样:

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)

我如何创建这些列表的总和?如在第一,14 + 2 + 16?

2 个答案:

答案 0 :(得分:0)

如前所述,取一个数字%的模数将产生余数。因此,如果n%2为0,则数字为偶数。你可以像这样实现sumEvens ......

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)

答案 1 :(得分:0)

这是一个非常基本的链表示例

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])

我认为iterFunctions是您最关心的问题