Skip to content

Added new algorithm to generate numbers in lexicographical order #11674

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Oct 5, 2024
Merged
38 changes: 38 additions & 0 deletions data_structures/stacks/lexicographical_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from collections.abc import Iterator


def lexical_order(max_number: int) -> Iterator[int]:
"""
Generate numbers in lexical order from 1 to max_number.

>>> " ".join(map(str, lexical_order(13)))
'1 10 11 12 13 2 3 4 5 6 7 8 9'
>>> list(lexical_order(1))
[1]
>>> " ".join(map(str, lexical_order(20)))
'1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9'
>>> " ".join(map(str, lexical_order(25)))
'1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 3 4 5 6 7 8 9'
>>> list(lexical_order(12))
[1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9]
"""

stack = [1]

while stack:
num = stack.pop()
if num > max_number:
continue

yield num
if (num % 10) != 9:
stack.append(num + 1)

stack.append(num * 10)


if __name__ == "__main__":
from doctest import testmod

testmod()
print(f"Numbers from 1 to 25 in lexical order: {list(lexical_order(26))}")