Created
December 14, 2019 18:47
-
-
Save jeremy-clearlabs/307a8059e0f6027d7c601dcd1e182dc2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # in: [1, 2, 3] | |
| # out: [1, 2, 3] | |
| # in: [1, [1, 2], 2, [3]] | |
| # out: [1, 1, 2, 2, 3] | |
| # Hint: You’ll need to use a for-loop somewhere. | |
| def flatten(l, new_list = None): | |
| # Base Case | |
| new_list = new_list or [] | |
| for item in l: | |
| if type(item) == list: | |
| flatten(item, new_list) | |
| else: | |
| new_list.append(item) | |
| return new_list | |
| # Return and calling flatten again | |
| print(flatten([1, [1, 2], 2, [3]])) | |
| # Call 1 ([1, [1, 2], 2, [3]], none) | |
| # For loop: [1, [1, 2], 2, [3]] | |
| # index 1, int, append | |
| # index 2, list, flatten | |
| # Call 2: ([1, 2], [1]) | |
| # For loop: [1, 2] | |
| # index 1, int, append | |
| # index 2, int, append | |
| # Call 1: | |
| # index 3, int, append | |
| # index 4, list, flatten | |
| # Call 2: ([3], [1, 1, 2, 2]) | |
| # index 1, int, append | |
| # Call 1: | |
| # return [1, 1, 2, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment