Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Stepping Number: Python Code

Friday, August 15, 2014

Stepping Number: Python Code

Python code for stepping number. A number is called
a stepping number if adjacent digits, as well as the
first and last digits, differ by 1.Write a program
to generate all the Stepping numbers( in base 11) in a given range and count it. For example, 8789A9 is a 6-digit base 11 stepping number. 9A0A and 234 are not stepping.

def SteppingNumber():
    numbDigits = [0 for i in range (10000)]
    counter = 0
    lowerLimit = int(input("Enter the lower limit:"))
    upperLimit = int(input("Enter the upper limit:"))
    for j in range(upperLimit+1-lowerLimit):
        flag = False
        numb = j+lowerLimit
        N = numb
        length = len(str(numb))
        baseElevenlen = 0
        b = 0
        while numb > 0 :
            rem = numb%11
            if rem > 9:
                numbDigits[baseElevenlen] = 'A'
            else:  
                numbDigits[baseElevenlen] = rem
            numb = numb//11
            baseElevenlen +=1
               
        numbDigits.reverse()          
        for i in range(baseElevenlen):
            if numbDigits[i] == 'A':
                numbDigits[i] = 10
           
        for i in range(baseElevenlen-1):
            if numbDigits[i] == numbDigits[i+1]+1 or numbDigits[i] == numbDigits[i+1]-1:
                flag = True
            else:
                flag = False
                break;  
           
        if flag == True:
            if numbDigits[0] == numbDigits[baseElevenlen-1]+1 or numbDigits[0] == numbDigits[baseElevenlen-1]-1:
                flag = True  
            else:
                flag = False  
        if flag == True:
            print (N-1," is a Stepping Number")
            print ("In base Eleven (Reverse it)", numbDigits[0:baseElevenlen])
            counter +=1
    print ("Number of stepping numbers(base 11)",counter)
SteppingNumber()

No comments:

Post a Comment