使用Python进行递归分配

时间:2014-11-11 00:12:19

标签: python recursion

我在使用递归时遇到了分配问题。我被困在如何使用Python设置递归。我有一个价值清单和两个人做公平分配(尽可能公平)。如果两个人之间的资产差异相等,则应将资产分配给第一个人。请查看我对设置递归的错误提出建议:

def Asset_Allocation(person1, person2, allocation, numLoops):
    '''Recursive Function to Assign Assets to People''' 
    #Value[0] or Value[1:]
    numLoops += 1
    print "Number of Loops:", numLoops
    num_items = len(Value) - len(allocation)
    d = person1 - person2
    if num_items == 0:
        return person1, person2, allocation
    elif d == 0 and numLoops < len(Value):
        allocation.append('Chuck')
        person1 = person1 + Value[numLoops - 1]
        Asset_Allocation(person1, person2, allocation, numLoops) 
    else:           
        m = (d + Asset_Allocation(person1, person2, Value[1:], numLoops))
        a = (d - Asset_Allocation(person1, person2, Value[1:], numLoops))
        if m < a:
            allocation.append('Chuck')
            person2 = person2 + Value[numLoops - 1]
        else: 
            allocation.append('Allison')            
            person1 = person1 + Value[numLoops -1]


    return person1, person2, allocation

import sys
sys.setrecursionlimit(2000)

#Create Tuples of Values    
Value = (2, 1, 3)

#Variables to Assign People
Chuck = 0
Allison = 0
Allocation = []

#Global Variable to track number of Recursive Calls
NumLoops = 0

# Call Asset Allocation Function to Solve the Problem
Chuck, Allison, Allocations = Asset_Allocation(Chuck, Allison, Allocation, NumLoops)

#Print Results
print 'Allocations:'
print Asset[0], Value[0], Allocations[0]
print Asset[1], Value[1], Allocations[1]
print Asset[2], Value[2], Allocation
print 'Allison Total', Allison
print Allocation

1 个答案:

答案 0 :(得分:0)

我不确定我是否收到您的问题,特别是您说的部分&#34; 如果两个人之间的资产差异相等,则应将资产分配给第一个人&#34;

所以我的理解是你想要在2个人之间尽可能公平地分配东西,第一个人获得任何超值。我想提出一个适用于此的解决方案:

def assets_allocation(alloc):

    def sub(alloc, lst1, tot1, lst2, tot2, results, diff):
        if alloc: # there's more to allocate
            head, tail = alloc[0], alloc[1:] # split between head and tail
            # recurse, first giving the value of head to person 1, then to person 2
            results, diff = sub(tail, lst1+[head], tot1+head, lst2, tot2, results, diff)
            results, diff = sub(tail, lst1, tot1, lst2+[head], tot2+head, results, diff)
        else:
            newdiff = tot1 - tot2
            if results and newdiff == diff: # same value as previous results, add
                return results+[(lst1, lst2)], newdiff
            elif not results or 0 <= newdiff < diff: # new value
                return [(lst1, lst2)], newdiff
        return results, diff

    results, diff = sub(alloc, [], 0, [], 0, [], None)
    return results

测试:

>>> assets_allocation((2, 1, 3)) # two results here
[([2, 1], [3]), 
 ([3], [2, 1])]

>>> assets_allocation((2, 1, 4)) # just 1 result
[([4], 
  [2, 1])]