python 编程题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuskyter/article/details/81136333

输入一个任意长度的整形数组,把它分成两个数组,要求使得这两个数组各自的和相同,如果不能相同,做到差距(各自之和的差的绝对值)最小,如果有多个解决方案,返回任意一个就行

import copy

def incomplete_solution(arr):
    total = sum(arr)
    half = total/2
    possibleSolution = {0: []}
    for i in arr:
        possibleSum = possibleSolution.keys()
        for k in list(possibleSum):
            now = i + k
            if (now not in possibleSum):
                valueList = possibleSolution[k]
                nowList = copy.copy(valueList)
                nowList.append(i)
                possibleSolution[now] = nowList
                if (now == half):
                    return nowList
    possibleSolution = {0: []}
    for i in arr:
        possibleSum = possibleSolution.keys()
        for k in list(possibleSum):
            now = i + k
            if (now not in possibleSum):
                valueList = possibleSolution[k]
                nowList = copy.copy(valueList)
                nowList.append(i)
                possibleSolution[now] = nowList
                if (now > half):
                    return nowList

if __name__ == '__main__':
    arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
    n = incomplete_solution(arr)
    for i in n:
        arr.remove(i)
    print(n)
    print(arr)


 

猜你喜欢

转载自blog.csdn.net/liuskyter/article/details/81136333