简体   繁体   English

使用递归检查列表中元组的总和

[英]Using Recursion to check for sum of tuples in a list

I have a func which takes a list of tuples, each tuple contains two items: item name and value.我有一个函数,它接受一个元组列表,每个元组包含两个项目:项目名称和值。 I need the func to return True if it's possible to divide the tuple list into two equal valued groups and False otherwise.如果可以将元组列表分成两个相等的值组,我需要 func 返回 True,否则返回 False。 The function should be recursive and should not use any loops. function 应该是递归的并且不应该使用任何循环。

for example,例如,

func([('tree', 500), ('keyboard', 200), ('pen', 300)])

should result in True , because the value of keyboard + pen = tree and it can be divided into two equal groups.应该是True ,因为keyboard + pen = tree 的值可以分成两个相等的组。

So far, what I managed to write is:到目前为止,我设法写的是:

def func(lst):
if len(lst) == 1 or len(lst) == 0:
    return False
elif len(lst) == 2:
    if lst[0][1] != lst[1][1]:
        return False
    else:
        return True

But it only covers the basic cases.但它只涵盖基本情况。 Any help would be appreicated.任何帮助将不胜感激。

Not very efficient for big lists, but I assume it is recursive because of school work:对于大列表不是很有效,但我认为它是递归的,因为学校工作:

def divide(lst, left_sum, right_sum):
    # if no more elements,
    # then it is true if  left_sum == right_sum else false
    if not lst:
        return left_sum == right_sum

    obj, value = lst[0]
    # element can go either left or right
    return divide(lst[1:],left_sum + value, right_sum) or divide(lst[1:],left_sum, right_sum+value)

assert divide([('tree', 500), ('keyboard', 200), ('pen', 300)],0,0)
assert not divide([('tree', 500), ('keyboard', 200), ('pen', 301)],0,0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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