Summing the Digits in an Integer using Python

Posted by Samath
  1520
March 02, 2015

 

Write recursive functions in python that calculate div and mod.
div takes two integers as input and keeps on subtracting the second from the first until the first number becomes less than the second number. The function keeps a track of how many times the second number is subtracted from the first and returns that number as the answer.

mod also takes two integers as input and keeps on subtracting the second from the first until the first number becomes less than the second number. When the first number becomes less than the second, the value of the first number is the answer.

Code:

def div(a,b):
    if(a<b):
        return 0
    else:
        return 1 + div(a-b,b)

def mod(a,b):
    if(a<b):
        return a
    else:
        return mod(a-b,b)

Two functions lastDigit and allButLast are given below. Given a number n as an argument the function lastDigit returns the last digit of that number and allButLast returns the number with its last digit taken off. Write a recursive function sumDigits which sums all digits in a given number. For example, 234 will be 2+3+4, hence 9 will be returned.

Given a number n extract the last digit and call the function with an argument from which the last digit has been removed.

def lastDigit(x):
  return mod(x,10)
  
def allButLast(x):
  return div(x,10)

Code:

def sumDigits(num):
    if(num < 10):
        return num 
    else: 
        return int((lastDigit(num))+sumDigits(allButLast(num)))

Write a python function is_valid that checks if the input is a valid Student id number. Valid student Id’s are in the range 1000-6999 and the sum of their digits should be divisible by 7. If the id number is valid return True otherwise return False.

Code:

def is_valid(n):
    if(n>=1000 and n<=6999):
        if(sumDigits(n)%7==0):
            return True
        else:
            return False
    else:
        return False