Skip to content

Instantly share code, notes, and snippets.

@SteadBytes
Created December 5, 2019 19:38
Show Gist options
  • Save SteadBytes/6cee224450318d4359a8a659d763d29c to your computer and use it in GitHub Desktop.
Save SteadBytes/6cee224450318d4359a8a659d763d29c to your computer and use it in GitHub Desktop.
import math
from itertools import islice
from typing import Iterable
def first_n_digits(num: int, n: int) -> Iterable[int]:
"""
Returns an iterable of the first `n` digits (left to right) in `num`
Examples:
>>> list(first_n_digits(12345, 5))
[1, 2, 3, 4, 5]
>>> list(first_n_digits(12345, 4))
[1, 2, 3, 4]
>>> list(first_n_digits(12345, 3))
[1, 2, 3]
>>> list(first_n_digits(12345, 2))
[1, 2]
>>> list(first_n_digits(12345, 1))
[1]
"""
return (
(num // (10 ** i)) % 10
for i in islice(range(math.ceil(math.log10(num)) - 1, -1, -1))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment