0

I'm trying to make a recursive function that gets rid of all the vowels in a list. For some reason my solution just returns an empty list and I don't understand how to fix it. Here is my code:

def remove(seq):
    if not seq:
        return []
    elif isinstance(seq[0], list):
        return remove(seq[0]) + remove(seq[1:])
    elif seq[0] == "a" or "e" or "i" or "o" or "u":
        return remove(seq[1:])
    else:
        return seq[0] + remove(seq[1:])

    print(remove(["a", "b", "c", ["d", "e"], "f"])) just returns []
user2831306
  • 33
  • 1
  • 6

1 Answers1

1

Here's a fixed version:

def remove(seq):
    if not seq:
        return []
    elif isinstance(seq[0], list):
        return [remove(seq[0])] + remove(seq[1:])
    elif seq[0] in ["a", "e", "i", "o", "u"]:
        return remove(seq[1:])
    else:
        return [seq[0]] + remove(seq[1:])

print(remove(["a", "b", "c", ["d", "e"], "f", "g", "h", "i"]))

Output:

['b', 'c', ['d'], 'f', 'g', 'h']

The first error was the way that you used the 'or' to compare with multiple values. You could write seq[0] == "a" or seq[0] == "b" or ..., or use an in and a sequence as I did. For better performance the vowels could be put into a set, like this:

vowels = {"a", "e", "i", "o", "u"}

def remove(seq):
    if not seq:
        return []
    elif isinstance(seq[0], list):
        return [remove(seq[0])] + remove(seq[1:])
    elif seq[0] in vowels:
        return remove(seq[1:])
    else:
        return [seq[0]] + remove(seq[1:])

print(remove(["a", "b", "c", ["d", "e"], "f", "g", "h", "i"]))

Your second error was with the last return statement. You tried to join a string to the front of a list with the + operator. Effectively you were doing something like "b" + ["c"], which throws an error. You can't add a list and a non-list together with +.

Thirdly, to maintain the structure of the nested lists, I had to wrap the return value of remove() in a list, in the case where we had a nested list return [remove(seq[0])] + remove(seq[1:]).

Galax
  • 1,441
  • 7
  • 6
  • You also need to return an empty string in first `if` condition. – Mazdak Nov 17 '15 at 16:22
  • That's because of that you have changed the the last condition to `[seq[0]]` – Mazdak Nov 17 '15 at 16:29
  • Can I do this in a way that the initial structure of the list remains intact? So if I have sublists in the list they would remain: [a, b, [c, d, e], f] would become [b, [c, d], f] – user2831306 Nov 17 '15 at 16:32
  • @Galax did you understand my question? Can I do this in a way that the initial structure of the list remains intact? So if I have sublists in the list they would remain: [a, b, [c, d, e], f] would become [b, [c, d], f] – user2831306 Nov 17 '15 at 16:41
  • @user2831306 I've updated my answer to return nested lists, instead of flattening to one list. – Galax Nov 17 '15 at 16:44