Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Generate First N Lexicographic Numbers in Python



Suppose we have a number n, we have to find first n numbers that are sorted in lexicographic sequence.

So, if the input is like n = 15, then the output will be [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]

To solve this, we will follow these steps:

  • count := 1
  • ans := a list with single element count
  • while size of ans
  • count := count * 10
  • while count > n , do
    • count := quotient of count / 10
    • count := count + 1
    • while count mod 10 is same as 0, do
      • count := quotient of count / 10
    • insert count at the end of ans
  • return ans
  • Let us see the following implementation to get better understanding:

    Example Code

    Live Demo

    class Solution:
       def solve(self, n):
          count = 1
          ans = [count]
    
          while len(ans)  n:
                count = count // 10
                count += 1
                while count % 10 == 0:
                   count = count // 10
                   ans.append(count)
                return ans
    
    ob = Solution()
    n = 15
    print(ob.solve(n))
    
    

    Input

    15

    Output

    [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]
    Updated on: 2020-11-25T12:48:34+05:30

    322 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements