简体   繁体   中英

Using linked lists to sum only even numbers?

I've been trying to use 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. My code right now 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
    ....


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?

@filmor is right..

Is this what you need?

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

Using your insertValueHead from your earlier question , you can implement sumEvens like this:

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

What this does is: It checks whether the current list is not None, gets the data value, checks whether it's even, and recursively returns the sum of that value and the sum of the remainder of the list.

However, looking at how you implement your list as a nested dictionary with 'data' and 'next' entries, I'd suggest using a class instead, and adapting your other methods accordingly.

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

You can create a generator that iterates over your list:

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

This assumes you have functions defined on your linked list type that get the first element (the head) and the rest (the tail).

Then you can use this to sum the even elements:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM