Step Number from 10 to N using python

后端 未结 4 1656
春和景丽
春和景丽 2021-01-21 18:04

The Program must accept an integer N. The program must print all the stepping number from 10 to N, if there is no such number present the program should print -1 as

4条回答
  •  一个人的身影
    2021-01-21 18:19

    Maybe the main trick here is that the max range is 10^7. If we consider each digit as a node of the graph, we can traverse it with bfs/dfs and at each point, we can only move to the adjacent node (digit + 1, digit -1). Because the maximum depth is only 7, the solution should be pretty fast.

    Here's a rough DFS implementation, you can improve the details.

    sol_list = []
    def dfs(i, num, N):
      # print(i, num)
      if num > N: # too much, need to break
        return
      if num <= N and num >= 10: # perfect range, add to solution, I can add some repeated solution as I called dfs(i+1,0,N) multiple times
        global sol_list
        # print(num)
        sol_list.append(num) # add to solution
    
      if i > 7:
        return
      if num == 0: # I can call another 0
        dfs(i+1, 0, N) # this is not needed if the numbers are added in the previous list without checking
      last_dig = num % 10
      if last_dig == 0:
          dfs(i+1, num*10 + 1, N) # if last digit is 0, we can only choose 1 as next digit not -1
      elif last_dig == 9:
        dfs(i+1, num*10 + 8, N)
      else:
        dfs(i+1, num*10 + (last_dig-1), N)
        dfs(i+1, num*10 + (last_dig+1), N)
    
    import time
    t1 = time.time()
    [dfs(0, i, 10000000) for i in range(10)] # staring with every digit possible 0-9
    t2 = time.time()
    print(t2-t1)
    sol = sorted(set(sol_list))
    print(sol) # added some repeated solutions, it's easier to set them
    

提交回复
热议问题