Skip to content

Instantly share code, notes, and snippets.

@fakuivan
Created April 12, 2021 04:35
Show Gist options
  • Save fakuivan/7f0f46808b7eb54c4631929766778adc to your computer and use it in GitHub Desktop.
Save fakuivan/7f0f46808b7eb54c4631929766778adc to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.9
from itertools import chain
from typing import Iterator
import argh
ichain = chain.from_iterable
def up_to_multiple(mul: int, val: int) -> int:
"""
Rounds a value up to the nearest multiple
"""
return val + (0 if val % mul == 0 else (mul - val % mul))
def booklet(pages: int, filler_page: int = 0) -> Iterator[int]:
"""
Returns a permutation representing the order of pages for a
booklet style print
"""
padded = up_to_multiple(4, pages)
for page in ichain((padded - i, i + 1, i + 2, padded - (i + 1)) for i in range(0, padded//2, 2)):
yield filler_page if page > pages else page
@argh.arg('pages', type=int, help='Number of pages')
# Argh! argh does not merge inferred parameters and given ones
#@argh.arg('filler_page', help='Filler number used for page numbers not multiple of 4')
#@argh.arg('separator', help='Separator between the permutation values')
def cmd_booklet(pages: int, filler_page: int = 0, separator: str = ','):
"""
Computes the permutation representing the order of pages
for a booklet style print
"""
return separator.join(str(page) for page in booklet(pages, filler_page))
if __name__ == '__main__':
argh.dispatch_command(cmd_booklet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment