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:])
.