使用链接列表仅对偶数求和?

时间:2014-08-05 08:30:54

标签: python python-2.7

我一直在尝试使用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
    ....


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?

3 个答案:

答案 0 :(得分:1)

@filmor是对..

这是你需要的吗?

def createList(*args):
    new_list=[]

    for arg in args: 
        new_list.append(arg)

    return new_list

def sumEvens(List):

    if List:
        return sum(x for x in List if x % 2 == 0)
    else:
        return "0"


def testSumEvens():
    myList = createList(14, 21, 29, 2, 16, 49, -26)

    print "The sum of the even numbers in the first list is {0}".format(sumEvens(myList))
    myList = createList()
    print "The sum of the even numbers in an empty list is {0}".format(sumEvens(myList))
    myList = createList(5, 15, 25)
    print "The sum of the even numbers in the final list is {0}".format(sumEvens(myList))

testSumEvens()

答案 1 :(得分:0)

使用your earlier question中的insertValueHead,您可以像这样实施sumEvens

def sumEvens(linkedList):
    if linkedList is not None:
        val = linkedList["data"]
        return (val if val % 2 == 0 else 0) + sumEvens(linkedList["next"])
    return 0

这样做:它检查当前列表是否为None,获取数据值,检查它是否为偶数,并递归返回该值的总和以及列表其余部分的总和。

但是,看看如何将列表实现为带有“数据”和“下一个”条目的嵌套字典,我建议使用类,并相应地调整其他方法。

class LinkedList:
    def __init__(self, head, tail):
        self.head = head
        self.tail = tail
    def __repr__(self):
        return "LinkedList(%r, %r)" % (self.head, self.tail)

def insertValueHead(linkedList, value):
    return LinkedList(value, linkedList)

def sumEvens(linkedList):
    if linkedList is not None:
        val = linkedList.head
        return (val if val % 2 == 0 else 0) + sumEvens(linkedList.tail)
    return 0

答案 2 :(得分:0)

您可以创建一个迭代列表的生成器:

def iter_list(xs):
    while xs is not None:
        yield get_head(xs)
        xs = get_tail(xs)

这假设您在链接列表类型上定义了获取第一个元素(头部)和其余元素(尾部)的函数。

然后你可以用它来对偶数元素求和:

def sum_evens(xs):
    return sum(x for x in iter_list(xs) if x % 2 == 0)