使用链表仅对偶数求和? [英] Using linked lists to sum only even numbers?
本文介绍了使用链表仅对偶数求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试在 python 中使用链表来根据列表中的偶数计算列表的总和.我已经为我相信的链表部分编写了代码,但我很难理解如何让它实际只取偶数并将它们相加.我的代码现在看起来像这样:
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)
我将如何着手创建这些列表的总和?比如第一个,14+2+16?
How would I go about making this create a sum of these lists? Such as in the first, 14 + 2 + 16?
推荐答案
@filmor 是对的..
@filmor is right..
这是您需要的吗?
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()
这篇关于使用链表仅对偶数求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文