Search code examples
pythonlistincrementdecrement

Python - Create a group of lists using numbers


say I have a string n = '22' and another number a = 4 so that n is a str and a is an int. I would like to create a group of lists like:

list1 = [22, 12, 2] #decreasing n by 10, the last item must be single digit, positive or 0
list2 = [22, 11, 0] #decreasing n by 11, last item must be single digit, positive or 0
list3 = [22, 21, 20] #decreasing n by 1, last item must have last digit 0
list4 = [22, 13] #decreasing n by 9, last item must be single digit. if last item is == a, remove from list
list5 = [22, 32] #increasing n by 10, last item must have first digit as a - 1
list6 = [22, 33] #increasing n by 11, last item must have first digit as a - 1
list7 = [22, 23] #increasing n by 1, last item must have last digit a - 1
list8 = [22, 31] #increasing n by 9, last item must have first digit a - 1

I am struggling on how to start this. Maybe you can give me an idea of how to approach this problem?

By the way if a condition cannot be satisfied, then only n will be on that list. say n = '20', a = 4:

list3 = [20]

Also this is for a school project, for indexes in a list which has list items. I can't think of a better way to approach the problem.


Solution

  • This should get you started:

    def lbuild( start, inc, test ):
        rslt = [start]
        while not test(start,inc):
            start += inc
            rslt.append( start )
        return rslt
    
    n = '22'
    a = 4
    
    nval = int(n)
    print lbuild( nval, -10, lambda(x,y): (x<10 and x>=0) )
    print lbuild( nval, 1, lambda(x,y): x%10 == a-1 )