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?

2
  • remove_all0 returns a list, which you're wrapping in another list when you call it recursively Commented Oct 11, 2015 at 12:24
  • I think this post might also be of interest stackoverflow.com/questions/1157106/… it shows how to efficiently remove all occurrences of an item from a list in Python. Commented Oct 11, 2015 at 13:00

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.