Skip to content Skip to sidebar Skip to footer

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 believ

Solution 1:

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 (valifval % 2 == 0else0) + sumEvens(linkedList["next"])
    return0

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.

classLinkedList:
    def__init__(self, head, tail):
        self.head = head
        self.tail = tail
    def__repr__(self):
        return"LinkedList(%r, %r)" % (self.head, self.tail)

definsertValueHead(linkedList, value):
    return LinkedList(value, linkedList)

defsumEvens(linkedList):
    if linkedList isnotNone:
        val = linkedList.head
        return (val if val % 2 == 0else0) + sumEvens(linkedList.tail)
    return0

Solution 2:

You can create a generator that iterates over your list:

defiter_list(xs):
    while xs isnotNone:
        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:

defsum_evens(xs):
    returnsum(x for x in iter_list(xs) if x % 2 == 0)

Post a Comment for "Using Linked Lists To Sum Only Even Numbers?"