python - How to write recursive function properly? -
im new python , therefore apologize if question ist basic:
i write function calculates minimum monthly payment needed in order pay off credit card balance within 12 months using recursion.
given following:
initialbalance = 1000 # thats initial balance on card / debt annualinterest = .2 startperiod = 1 # when start begin pament minmonthpayment = 5 # begin monthly payment of 5 $ def repayment(initialbalance,annualinterest,minmonthpayment,startperiod): while startperiod < 12 , initialbalance > 0: monthrate = annualinterest/12 interest = monthrate * initialbalance initialbalance -= minmonthpayment initialbalance += interest startperiod += 1 # here check if still havent paid off balance initial 5 dollars # if not call function again , increase minmonthpayment if initialbalance > 0: repayment(initialbalance, annualinterest, minmonthpayment + 5, startperiod) return round(initialbalance,1) print(repayment(1000,.2,5,1))
however doesnt seem call function appropriately , return:
recursionerror: maximum recursion depth exceeded in comparison
when coding recursive functions have first answer question when function stop going deeper , return value. check first few lines of recursive function.
so first should check if function should stop, , if doesn't need stop, is, if should go deeper have change parameters pass down make sure satisfies condition.
for example simple recursive function print elements of list this:
def print_list_recursive(list): # condition answers question 'do need go deeper?' if list empty: # don't go deeper return else: # have go deeper first_element = remove_first_element(list) print first_element print_list_recursive(list) # list parameter changed
note how parameter list
changes every time go deeper. each time 1 element removed list empty , return (stop going deeper).
recursion seem easy once define problem recursively , define stopping condition.
in "print list" problem should see print list can print first element , call print_list on rest of list, again prints first element , calls print_list on rest of list... when stop? when stopping condition, is, when list empty.
this same logic can apply when coding recursive function.
i hope helps.
Comments
Post a Comment