python 3.x - Recursive function doesn't return created string -


i new @ python, maybe can silly question.

i've implemented simple recursive knapsack solution returns bit sequence eventually. not return sequence generated. here code , results different inputs.

def knapsackrecursive(items, maxnum, bestresponse):     print('items=' + str(items) + ', maxnum=' + str(maxnum))     referenceindex = 0     editablemaxnum = maxnum     if editablemaxnum == 0:         bestresponse = '0'     else:         in reversed(items):             item = int(i)             if editablemaxnum >= item:                 if referenceindex == 0:                     referenceindex = items.index(str(item))                 editablemaxnum -= item                 bestresponse = '1' + bestresponse             else:                 bestresponse = '0' + bestresponse         if editablemaxnum != 0:             bestresponse = ''             if referenceindex != 0:                 k in range(0, len(items) - referenceindex):                     bestresponse = '0' + bestresponse                  knapsackrecursive(items[:referenceindex], maxnum, bestresponse)             else:                 bestresponse = '0'      print('bestresponse=' + str(bestresponse))     return bestresponse 

items constants ['1', '2', '4', '10', '20', '40', '63', '105']. initial bestresponse empty string.

if set maxnum 41, output is:

items=['1', '2', '4', '10', '20', '40', '63', '105'], maxnum=41 bestresponse=10000100 

but if set maxnum 71, output is:

items=['1', '2', '4', '10', '20', '40', '63', '105'], maxnum=71 items=['1', '2', '4', '10', '20', '40'], maxnum=71 bestresponse=10011100 bestresponse=00 

why bestresponse output printed twice input 71? , although first print right, why function returns second result wrong?

edit

i have changed knapsackrecursive(items[:referenceindex], maxnum, bestresponse) return knapsackrecursive(items[:referenceindex], maxnum, bestresponse). seems resolved. made mistake when using recursive. still couldn't understand why function returns result of first call instead of second call expected generate right response.

i think should do:

best_response = knapsackrecursive(items[:referenceindex], maxnum, bestresponse) 

instead of

knapsackrecursive(items[:referenceindex], maxnum, bestresponse) 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -