Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions data_structures/stacks/lexicographical_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
def lexical_order(n: int) -> str:
"""
Generate numbers in lexical order from 1 to n and return them as a space-separated string.

Check failure on line 3 in data_structures/stacks/lexicographical_numbers.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

data_structures/stacks/lexicographical_numbers.py:3:89: E501 Line too long (94 > 88)

>>> lexical_order(13)
'1 10 11 12 13 2 3 4 5 6 7 8 9'
>>> lexical_order(1)
'1'
>>> lexical_order(20)
'1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9'
>>> 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'
"""

ans = []
stack = [1]

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

Check failure on line 22 in data_structures/stacks/lexicographical_numbers.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/stacks/lexicographical_numbers.py:22:1: W293 Blank line contains whitespace
ans.append(str(num))
if (num % 10) != 9:

Check failure on line 24 in data_structures/stacks/lexicographical_numbers.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

data_structures/stacks/lexicographical_numbers.py:24:28: W291 Trailing whitespace
stack.append(num + 1)

stack.append(num * 10)

return " ".join(ans)

if __name__ == "__main__":

Check failure on line 32 in data_structures/stacks/lexicographical_numbers.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/stacks/lexicographical_numbers.py:32:1: W293 Blank line contains whitespace
from doctest import testmod

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