0
재귀를 사용하여 할당 문제가 발생했습니다. 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
당신이되고'd','m' 및'A'를 기대 설명 코멘트 몇 것 도움이 되십시오 ...'d = 차이'? – Basic
D는 차이입니다. 나는 자산 할당을 추적하기 위해 m과 a를 사용할 필요가 있었다. d> = 0 인 경우, (d + 자산 가치, d- 자산 가치) 분에 기초하여 d <0을 할당해야한다면 최대 (d + 자산 가치, d- 자산 가치)를 사용해야합니다. –
else case의 경우, Asset_Allocation에 대한 호출의 반환 값인 스칼라 d를가집니다. Asset_Allocation은 값의 튜플을 반환합니다. 이 동작은 오류를 throw합니다. – mobiusklein