Skip to content

Instantly share code, notes, and snippets.

@sloanlance
Last active November 1, 2023 18:45
Show Gist options
  • Save sloanlance/522952e01975ebd9d744c6ca8b60646c to your computer and use it in GitHub Desktop.
Save sloanlance/522952e01975ebd9d744c6ca8b60646c to your computer and use it in GitHub Desktop.
A Python class before and after optimization, as inspired by GitHub Copilot.
class IndexFormatter:
def __init__(self, volumeId: int):
self.itemPages = (
ItemPage.objects.filter(volume__id=volumeId)
.order_by('item__topic__name', F('page') * 1, 'item__name'))
def format(self) -> str:
"""
Format the index for printing.
"""
previousLetter = ''
indexText = ''
# unable to use `.distinct()` here for some reason
# using `list(dict.fromkeys(…))` trick to mimic an ordered set
topics = list(dict.fromkeys(self.itemPages.values_list(
'item__topic__id', 'item__topic__name')))
for topicId, topicName in topics:
if topicName[0].upper() != previousLetter:
previousLetter = topicName[0].upper()
indexText += f'\n{previousLetter}\n\n'
indexText += (
f'{topicName}, '
+ '; '.join([f'{itemName}, {page}' for page, itemName in
self.itemPages.filter(item__topic=topicId)
.values_list('page', 'item__name')])
+ '\n')
return indexText
class IndexFormatter:
def __init__(self, volumeId: int):
self.itemPages = (
ItemPage.objects.filter(volume__id=volumeId)
.order_by('item__topic__name', F('page') * 1, 'item__name'))
def format(self) -> str:
"""
Format the index for printing.
"""
previousLetter = ''
indexText = ''
for (topic, topicLetter), itemPages in groupby(
self.itemPages, lambda ip: (
(n := ip.item.topic.name), n[0].upper())):
indexText += (
(f'\n{(previousLetter := topicLetter)}\n\n'
if previousLetter != topicLetter else '')
+ f'{topic}, '
+ '; '.join([f'{itemPage.item.name}, {itemPage.page}'
for itemPage in itemPages])
+ '\n')
return indexText
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment