I tried below piece of code:
def split(arr,i=0):
if i==0:
print("hey")
splitted=[]
print('splitted initialized')
a1=arr[:len(arr)//2]
a2=arr[len(arr)//2:]
if len(a1)>2:
print("splitting "+str(a1))
i+=1
split(a1,i)
else:
print("not splitting "+str(a1))
splitted.append(a1)
if len(a2)>2:
print("splitting "+str(a2))
i+=1
split(a2,i)
else:
print("not splitting "+str(a2))
splitted.append(a2)
return(splitted)
I am getting the below error when I execute:
split([1,2,3,4,6,7,8,54,76,3,4,5,67,78,8,7,45,2]) I expected the empty list "splitted" to be initializes only once during 0th initialization
hey
splitted initialized
splitting [1, 2, 3, 4, 6, 7, 8, 54, 76]
splitting [1, 2, 3, 4]
not splitting [1, 2]
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
split([1,2,3,4,6,7,8,54,76,3,4,5,67,78,8,7,45,2])
File "\Documents\python_projects-20170821\python_projects\sorting_algorithms\merge_sort\merge_sort.py", line 15, in split
split(a1,i)
File "\Documents\python_projects-20170821\python_projects\sorting_algorithms\merge_sort\merge_sort.py", line 15, in split
split(a1,i)
File "\Documents\python_projects-20170821\python_projects\sorting_algorithms\merge_sort\merge_sort.py", line 18, in split
splitted.append(a1)
UnboundLocalError: local variable 'splitted' referenced before assignment
I am able to overcome by nesting the this function within another function as shown below:
below code works fine on calling: splitter([1,2,3,4,6,7,8,54,76,3,4,5,67,78,8,7,45,2])
def splitter(arr):
splitted=[]
def split(arr):
a1=arr[:len(arr)//2]
a2=arr[len(arr)//2:]
if len(a1)>2:
print("splitting "+str(a1))
split(a1)
else:
print("not splitting "+str(a1))
splitted.append(a1)
if len(a2)>2:
print("splitting "+str(a2))
split(a2)
else:
print("not splitting "+str(a2))
splitted.append(a2)
return(splitted)
return split(arr)
I just want to understand why my first version of code dosen't work?
iis greater than zero and sosplit()will not definesplittedand so you get your error.i=0not for every other case in the recursive callsplitit definessplitted, does not mean that all recursive calls can seesplitted.