mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-10-05 21:29:29 +00:00
Compare commits
3 Commits
b7d2685657
...
04956d8694
Author | SHA1 | Date | |
---|---|---|---|
|
04956d8694 | ||
|
5a8655d306 | ||
|
8db8f5b24b |
38
data_structures/stacks/lexicographical_numbers.py
Normal file
38
data_structures/stacks/lexicographical_numbers.py
Normal file
|
@ -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))}")
|
|
@ -26,6 +26,15 @@ def quick_sort(collection: list) -> list:
|
|||
[]
|
||||
>>> quick_sort([-2, 5, 0, -45])
|
||||
[-45, -2, 0, 5]
|
||||
|
||||
Time Complexity:
|
||||
Best Case: O(n log n)
|
||||
Average case: O(n log n)
|
||||
Worst Case: O(n^2)
|
||||
|
||||
Space Complexity:
|
||||
Best Case: O(log n)
|
||||
Worst Case: O(n)
|
||||
"""
|
||||
# Base case: if the collection has 0 or 1 elements, it is already sorted
|
||||
if len(collection) < 2:
|
||||
|
|
Loading…
Reference in New Issue
Block a user