Created
November 28, 2022 23:40
-
-
Save wpcarro/99eb8f9ae8061eeb316999143a812d11 to your computer and use it in GitHub Desktop.
Python immutable list type (generated with OpenAI's text-davinci-003 model)
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
| """ | |
| 1. Define an immutable list type. | |
| 2. Create a library for manipulating the list. | |
| """ | |
| # Answer | |
| # 1. Define an immutable list type | |
| class ImmutableList: | |
| def __init__(self, items): | |
| self.items = tuple(items) | |
| def __getitem__(self, index): | |
| return self.items[index] | |
| def __len__(self): | |
| return len(self.items) | |
| def __repr__(self): | |
| return "ImmutableList({})".format(self.items) | |
| def __iter__(self): | |
| return iter(self.items) | |
| # 2. Create a library for manipulating the list | |
| def append_immutable(ilist, item): | |
| return ImmutableList(ilist.items + (item,)) | |
| def insert_immutable(ilist, index, item): | |
| return ImmutableList(ilist.items[:index] + (item,) + ilist.items[index:]) | |
| def remove_immutable(ilist, item): | |
| return ImmutableList(tuple(x for x in ilist.items if x != item)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment