Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python recursive sum of digit

def sum_digits(num: int) -> int:
	
	#base case when your "positive" integer get to 0
    if num == 0: 
        return 0
    #base case when your "negative" integer get is between -10 and 0
    if num > -10 and num < 0:
        return num
	
	# recursion for positive integer
    elif num > 0:
        return (num % 10) + sum_digits(num//10)
	
	# recursion for negative integer
    elif num < 0:
        return -(abs(num) % 10) + sum_digits(-(abs(num)//10))
      
sum_digits(123) # returns 6
sum_digits(-123) # returns -6
Comment

PREVIOUS NEXT
Code Example
Python :: import error in same directory python 
Python :: install python 3.6 on centos 
Python :: what does class meta do in django 
Python :: mouse bottom in pygame 
Python :: json to base64 python 
Python :: instabot python 
Python :: python get date from unix timestamp 
Python :: __call__ python 
Python :: numpy sort array by another array 
Python :: how to create a tuple from csv python 
Python :: extend tuple python 
Python :: python tkinter scrollbar widget 
Python :: get the name of a file using os 
Python :: python array to string 
Python :: Set a random seed 
Python :: pandas backfill 
Python :: pandas change to first day 
Python :: grid search cv 
Python :: how to add vertical line on subplot in matplotlib 
Python :: python sqlite 
Python :: how to select a single cell in a pandas dataframe 
Python :: commentaire python 
Python :: python remove special characters from list 
Python :: creating data frame in python with for loop 
Python :: is there a way to skip the first loop on a for loop python 
Python :: hardest python questions 
Python :: get prime number python 
Python :: python 2 deprecated 
Python :: selenium get parent element 
Python :: python summary() 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =