Hi I'm new to programming and I'm learning python. I'm currently learning recursion and I'm finding it kind of difficult. I found this exercise:
- Write a function "flatten" that returns a simple list containing all the values in a nested list
Then the exercise gives these test runs:
test(flatten([2,9,[2,1,13,2],8,[2,6]]) == [2,9,2,1,13,2,8,2,6])
test(flatten([[9,[7,1,13,2],8],[7,6]]) == [9,7,1,13,2,8,7,6])
test(flatten([[9,[7,1,13,2],8],[2,6]]) == [9,7,1,13,2,8,2,6])
test(flatten([["this",["a",["thing"],"a"],"is"],["a","easy"]]) == ["this","a","thing","a","is","a","easy"])
test(flatten([]) == [])
I did this:
new_list = []
def flatten(a_list):
for e in a_list:
if type(e) != type([]):
new_list.append(e)
if type(e) == type([]):
flatten(e)
print(new_list)
return new_list
and then added new_list.clear() between all the test runs like this:
test(flatten([2,9,[2,1,13,2],8,[2,6]]) == [2,9,2,1,13,2,8,2,6])
new_list.clear()
test(flatten([[9,[7,1,13,2],8],[7,6]]) == [9,7,1,13,2,8,7,6])
new_list.clear()
test(flatten([[9,[7,1,13,2],8],[2,6]]) == [9,7,1,13,2,8,2,6])
new_list.clear()
test(flatten([["this",["a",["thing"],"a"],"is"],["a","easy"]]) ==
["this","a","thing","a","is","a","easy"])
new_list.clear()
test(flatten([]) == [])
new_list.clear()
It works.
The problem is I feel like there's a better way to do it so I'm asking for help so that I can learn from you. Thanks for the help.
Edit: The "print(new_list)" part was me trying to understand what was going on in the program.