Step Number from 10 to N using python

后端 未结 4 1685
春和景丽
春和景丽 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:43

    You can simplify the generation of numbers by noting that each time a digit is added to an existing stepping number it must be either 1 more or 1 less than the existing last digit. So we can generate all the stepping numbers with a given number of digits by starting with single digit numbers (1-9) and then repeatedly adding digits to them until we have reached the number of digits we want. So for example, starting with the digit 1, and needing to go to 4 digits, we would produce

    1 => 10, 12
    10, 12 => 101, 121, 123
    101, 121, 123 => 1010, 1012, 1210, 1212, 1232, 1234
    

    The number of digits we need is computed by using math.ceil(math.log10(N)).

    import math
    
    def stepNums(N):
        if N < 10:
            return -1
        digits = math.ceil(math.log10(N))
        sn = [[]] * digits
        # 1 digit stepping numbers
        sn[0] = list(range(1, 10))
        # m digit stepping numbers
        for m in range(1, digits):
            sn[m] = []
            for s in sn[m-1]:
                if s % 10 != 0:
                    sn[m].append(s * 10 + s % 10 - 1)
                if s % 10 != 9:
                    sn[m].append(s * 10 + s % 10 + 1)
        return [s for l in sn for s in l if 10 <= s <= N]
    

    e.g.

    print(stepNums(3454))
    

    Output:

    [10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98, 101, 121, 123, 210, 212, 232, 234, 321, 323, 343, 345, 432, 434, 454, 456, 543, 545, 565, 567, 654, 656, 676, 678, 765, 767, 787, 789, 876, 878, 898, 987, 989, 1010, 1012, 1210, 1212, 1232, 1234, 2101, 2121, 2123, 2321, 2323, 2343, 2345, 3210, 3212, 3232, 3234, 3432, 3434, 3454]
    

    Note that the code could potentially be sped up by comparing the generated numbers to N so that when calling stepNums(10001) we don't generate all the numbers up to 98989.

提交回复
热议问题