File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ def lexicalOrder (n : int ) -> str :
2
+ """
3
+ Generate numbers in lexical order from 1 to n and return them as a space-separated string.
4
+
5
+ >>> lexicalOrder(13)
6
+ '1 10 11 12 13 2 3 4 5 6 7 8 9'
7
+ >>> lexicalOrder(1)
8
+ '1'
9
+ >>> lexicalOrder(20)
10
+ '1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9'
11
+ >>> lexicalOrder(25)
12
+ '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'
13
+ """
14
+ ans = []
15
+ stack = [1 ]
16
+
17
+ while stack :
18
+ num = stack .pop ()
19
+ if num > n :
20
+ continue
21
+
22
+ ans .append (str (num ))
23
+ if (num % 10 ) != 9 :
24
+ stack .append (num + 1 )
25
+
26
+ stack .append (num * 10 )
27
+
28
+ return " " .join (ans )
29
+
30
+ if __name__ == "__main__" :
31
+
32
+ from doctest import testmod
33
+
34
+ testmod ()
35
+ print (f"Numbers from 1 to 25 in lexical order: { lexicalOrder (25 )} " )
You can’t perform that action at this time.
0 commit comments