0
def remove_all1(x,s):
    def loop(x,s,ss):
        while s!=[]:
            if x == s[0]:
                return loop(x,s[2:],ss+[s[1]])
            else:
                return loop(x,s[1:],ss+[s[0]])
        return ss
    return loop(x,s,[])

This is the one I made by recursive tail function to remove recursive value x and if :

print(remove_all1(3,[4,3,5,6,3,2,1]))

I would get:

[4,5,6,2,1]

The exact result I want. But for the recursive function here:

def remove_all0(x,s):
    while s!=[]:
        if x == s[0]:
            ss = [s[1]] + remove_all0(x,s[2:])
            return ss 
        else:
            s1 = [s[0]] + [remove_all0(x, s[1:])]
            return s1 
    if s==[]:
        return s
print(remove_all0(3,[4,3,5,6,3,2,1]))

I would not get the same result. Instead, I got:

[4, [5, 6, [2, 1, []]]]

Why does this happen?

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
J.Doe
  • 71
  • 2
  • 9
  • `remove_all0` returns a list, which you're wrapping in another list when you call it recursively – jonrsharpe Oct 11 '15 at 12:24
  • I think this post might also be of interest http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list it shows how to efficiently remove all occurrences of an item from a list in Python. – Anthony Blackshaw Oct 11 '15 at 13:00

1 Answers1

2

The problem is in your else clause when you wrap the returned value from remove_all0 which is a list, and make it a list containing that list. Just remove those square brackets and you'll get the results you want:

def remove_all0(x,s):
    while s!=[]:
        if x == s[0]:
            ss = [s[1]] + remove_all0(x,s[2:])
            return ss
        else:
            s1 = [s[0]] + remove_all0(x, s[1:])
            return s1
    if s==[]:
        return s
print(remove_all0(3,[4,3,5,6,3,2,1]))

gives

[4, 5, 6, 2, 1]
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67