Recursive Function in Python

A recursive function is powerful as it allows calling itself multiple times until a termination condition is fulfilled.

To illustrate, we can use a factorial calculation as an example:

4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1

so the function can be writen

def factorial(n):
print(“factorial has been called with n = ” + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print(“intermediate result for “, n, ” * factorial(” ,n-1, “): “,res)
return res
print(factorial(5)):

Now we apply the same principle to the index weight capping rule – “that individual security weight is capped at a threshold% and no more than two securities are at that cap. The excess weight of any capped security is redistributed proportionally among remaining securities whose weights are less than threshold%. If this redistribution leads to additional security weights exceeding threshold%, the aforementioned redistribution process is repeated iteratively until no security weight exceeds threshold%.”

file = final[final.date == 20170602]
sum = file[‘adj_market_cap_($Mil_USD)’].sum()
file = file.sort_values(by=’adj_market_cap_($Mil_USD)’, ascending=False)
file[‘weight’] = file[‘adj_market_cap_($Mil_USD)’]/sum
Capping(file)

def Capping(file):

while (file.weight > threshold).any():
print(‘First round, Does any cells greater than %s? Yes!, Hence Cap it ‘+ ‘ time’) %(threshold)
largest = float(file.weight.nlargest(1))
file[‘weight_1’] = 0
file[‘weight_1’][file.weight == threshold] = threshold
file[‘weight_1’][file.weight == largest] = threshold
dist = largest – threshold
total = file.weight[(file.weight_1 == 0)].sum()
file[‘weight_1’][file.weight_1 == 0] = file.weight + dist*(file.weight/total)
#file.weight_1.sum()
del file[‘weight’]
file.rename(columns={‘weight_1’: ‘weight’}, inplace=True)
return Capping(file)

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s