1. 程式人生 > >python 程式設計題

python 程式設計題

輸入一個任意長度的整形陣列,把它分成兩個陣列,要求使得這兩個陣列各自的和相同,如果不能相同,做到差距(各自之和的差的絕對值)最小,如果有多個解決方案,返回任意一個就行

 

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)