Recursion error Python -
i wrote little bit code seek search word in list. it's not final version , can't yet. however, don't understand wrong code:
def findword (word, t): t.sort() midword = t[len(t)/2] midindex = len(t)/2 if word > midword: del t[:midindex] findword (word, t) elif word < midword: del t[midindex+1:] findword (word, t) elif word == midword: homecoming t else: homecoming none mydic=['apple','banana','peach','pear','melon','lemon','grape','berry'] mydic1 = findword('apple', mydic)
i got runtimeerror: maximum recursion depth exceeded in cmp
error when tried search apple
, when search other words in list, returns empty list.
please help me figure out wrong. thanks!
take @ code segment:
elif word < midword: del t[midindex+1:] findword (word, t)
in code, come point list reduced 2 elements, is:
t == ['apple', 'banana']
in case, take @ next interactive session:
in [15]: t = ['apple', 'banana'] in [16]: midindex = len(t)/2 in [17]: midindex out[17]: 1 in [18]: t[midindex+1:] out[18]: [] in [19]: del t[midindex+1:] in [20]: t out[20]: ['apple', 'banana']
notice in line 19, deleted nothing, t
remains same, called findword
same list , run infinite recursion until run out of stack space. should redesign code overcome problem.
another problem see called findword
recursively, did not create utilize of homecoming value. instead of:
elif word < midword: del t[midindex+1:] findword (word, t)
you should do:
elif word < midword: del t[midindex+1:] homecoming findword (word, t)
additional suggestions do not set t.sort()
within findword
function. sorting expensive, should once, outside of findword
. as others pointed out, bad practice modify list, instead redesign code not that if not homework or exercise, suggest utilize set
if want fast look-up python has library module called bisect
binary search. python recursion
No comments:
Post a Comment