am trying to design an abstract function that filter a list of Generic Type X (listofX) based on a predicate, and i pass that predicate as a function (fn)
when i call my function first time it succeed as i intend but the after that it preserve the answer and append upon it.
def positive(x):
return x>0
def negative(x):
return x<0
#PROBLEM# i CAN NOT reset filtered_list
def filter2(fn, listofX, i=0, filtered_list = []):
if i == len(listofX)-1:
return filtered_list
if fn(listofX[i]):
filtered_list.append(listofX[i])
i += 1
return filter2(fn, listofX, i)
numbers = [3 ,-2, -8, 4, -1, 2, 0]
print(filter2(positive, numbers)) #[3, 4, 2]
print(filter2(negative, numbers)) #[3, 4, 2, -2, -8, -1]
one way i try to solve it is every re start at i=0, i reset the list but it did not work for me:
def filter2(fn, listofX, i=0, filtered_list = []):
if i == 0:
filtered_list = []
if i == len(listofX)-1:
return filtered_list
if listofX[i] > 0:
filtered_list.append(listofX[i])
i += 1
return filter2(fn, listofX, i)
numbers = [3 ,-2, -8, 4, -1, 2, 0]
print(filter2(positive, numbers)) #[3, 4, 2]
print(filter2(negative, numbers)) #[3, 4, 2, -2, -8, -1]
Any help? what concept I miss dealing with here?