python - Output List Duplicating Values -


my function same_num takes values common both sorted lists , appends them onto 'result'. it's using recursion , 2 offsets, pos1 , pos2 set 0, compare values in list. when running function, works fine first time, if run function second time, original result appended answer got running initially. going wrong?

result=[]  def same_num(list1,list2,pos1,pos2):     list1=sorted(list1)     list2=sorted(list2)      if pos1==len(list1) or pos2==len(list2):         return result     if list1[pos1]==list2[pos2]:         result.append(list1[pos1])         return same_num(list1,list2,pos1+1,pos2+1)         if list1[pos1]>list2[pos2]:         return same_num(list1,list2,pos1,pos2+1)     if list1[pos1]<list2[pos2]:         return same_num(list1,list2,pos1+1,pos2) 

for example:

same_num([3,1,2,4],[3,1,2,4,5,6],0,0)=>[1,2,3,4] 

rerunning previous example in shell produces:

same_num([3,1,2,4],[3,1,2,4,5,6],0,0)=>[1, 2, 3, 4, 1, 2, 3, 4] 

when should still produce:

[1,2,3,4] 

the problem result global variable. globals bad! adding stuff result (result.append(...)) never clearing out after first invocation of same_num function.

(although can see why taking approach, because conceptually easier approach recursive functions using global variables.)

if make result parameter of same_num function can passed recursive invocations of same function... issue fixed.

def same_num(list1,list2,pos1,pos2,init_result=none):     # important: see remark below on why init_result=[]     # not expect     result = init_result if init_result not none else []      list1=sorted(list1)     list2=sorted(list2)      if pos1==len(list1) or pos2==len(list2):         return result     if list1[pos1]==list2[pos2]:         result.append(list1[pos1])         return same_num(list1,list2,pos1+1,pos2+1,result)         if list1[pos1]>list2[pos2]:         return same_num(list1,list2,pos1,pos2+1,result)     if list1[pos1]<list2[pos2]:         return same_num(list1,list2,pos1+1,pos2,result)  # multiple invocations return same (expected) result print( same_num([3,1,2,4],[3,1,2,4,5,6],0,0) ) print( same_num([3,1,2,4],[3,1,2,4,5,6],0,0) ) 

by way, see "common python gotchas: mutable default arguments" why used init_result=none default, rather init_result=[].


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -