This is supposed to be a program in Python which returns the position of a target element in a list recursively:
def linear_search_arrayList(arr, target, arr2 = [], num = 0):
if(len(arr) == num):
return arr2
elif(arr[num]==target):
return linear_search_arrayList(arr,target, arr2.append(num) , num 1)
else:
return linear_search_arrayList(arr,target, arr2, num 1)
array_list = [1,2,3,4,6,7,4,9]
print(linear_search_arrayList(array_list, 4))
This program returns an error
AttributeError: 'NoneType' object has no attribute 'append'
CodePudding user response:
this is because you are passing to linear_search_arrayList the arr2.append(num) argument, witch returns None, so you are passing the None argument to the function, since you cannot append a value to a NoneType object, you cannot pass that.
if your purpose was to add to the list and then pass it through the function, you can do:
def linear_search_arrayList(arr, target, arr2 = [], num = 0):
if(len(arr) == num):
return arr2
elif(arr[num]==target):
return linear_search_arrayList(arr,target, arr2 [num] , num 1)
else:
return linear_search_arrayList(arr,target, arr2, num 1)
array_list = [1,2,3,4,6,7,4,9]
print(linear_search_arrayList(array_list, 4))
CodePudding user response:
This code had several issues.
- The name
linear_search_arrayListdoes not fit Python's style guidelines; functions have lowercase names (in the snake_case format) - You had unnecessary parentheses in your
ifanelifstatements. - Having
arr2 = Nonein your function arguments means thatarr2will always point to the same list, which is generated once the moment the program is run. If you want it to be a new, empty list every time, you have to explicitly create a new list. A good practice for this is to set the default value toNone, then check for that withis None. You should not do== Nonebecause that is not good practice in Python (explanation). - The
appenderror was happening becauseappendreturns nothing; it affects the original list. If you want to append something to a list, you can either do it beforehand likearr2.append(num), or doarr2 [num]if you don't want to affectarr2.
With all that in mind, here is my attempt at fixing your code; you'll have to determine if it functions how you want, though.
def linear_search_array_list(arr, target, arr2=None, num=0):
if arr2 is None:
arr2 = []
if len(arr) == num:
return arr2
elif arr[num] == target:
return linear_search_array_list(arr, target, arr2 [num], num 1)
else:
return linear_search_array_list(arr, target, arr2, num 1)
array_list = [1, 2, 3, 4, 6, 7, 4, 9]
print(linear_search_array_list(array_list, 4))
