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 (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
Solution 2:
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)
Post a Comment for "Using Linked Lists To Sum Only Even Numbers?"