Last active
June 1, 2021 19:08
-
-
Save t-eckert/a31f61bbc2e1da5ad63eb1293bd776f4 to your computer and use it in GitHub Desktop.
Haskell's `inits` in Python
This file contains 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
from typing import Iterable | |
def inits(items: Iterable) -> list[Iterable]: | |
"""Given an iterable, returns all of its prefixes in ascending order of length | |
Arguments: | |
items: Iterable items whose prefixes will be returned | |
Returns: | |
list[Iterable] prefixes of the iterable | |
Example: | |
``` python | |
inits([4, 3, 2, 1]) # returns [[], [4], [4,3], [4,3,2], [4,3,2,1]] | |
``` | |
""" | |
return [items[:n] for n in range(len(items) + 1)] | |
numbers = [4, 3, 2, 1] | |
print(inits(numbers)) | |
letters = "abcdefg" | |
print(inits(letters)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment