#2 Recursive Digit Sum:

date posted: 2020-05-01




TMI of the day

  1. Very very tiring day, could not focus therefore came to cafe nearby.
  2. Never knew I would say this but I kinda miss Toronto :(
  3. Must adore place I am currently in and be thankful, always! :)



Solutions

For those of you who do not know what recursive algorithm, reading this will help --> What is Recursive algorithm

#1 Try
  • First, I created a base case so that I know that my recusive function will terminate.
  • When len(sup_digit) != 1 then we goto else statement and get sum of current sup_digit and call superDigit function recursively until it reaches base case.
def sum_digit(sup_digit):
    total = 0
    for number in sup_digit:
        total += int(number)
    return str(total)

# Complete the superDigit function below.
def superDigit(n, k):
    sup_digit = n*k

    # base case
    if len(sup_digit) == 1:
        return str(sup_digit) 
    
    else:
        summed_digit = sum_digit(sup_digit)
        return str(superDigit(summed_digit, 1))
    
  • Passes 7/11 test cases.

#1 Solution
  • using map function.
    • list(string) gives list of characters
    • map(int, list) = changes elements in list to integers
    • sum(map(int, list)) = since all are in int we can simply sum them. ex: "123" = 1+2+3 = 6
    • change back to string since it has to be passed into recursive function.
def superDigit(n, k):
    sup_digit = str(sum(map(int, list(n))) * k)

    # create base case
    if len(sup_digit) == 1:
        return int(sup_digit) 
    
    else:
        return int(superDigit(sup_digit, 1))
  • I guess using
    sup_digit = str(sum( map(int, list(n*k)) )) 
    gives a runtime error because having "123"*10^5 then summing each individual number would take much longer then sum([1,2,3])*10^5

#2 Solution

So if summing n then multiplying k to it was the trick then my original code should work as well. Previously I've multiplied n*k then summed all individual characters but just like 1st solution let me sum(n)*k and see if it works(I know it works...)

def sum_digit(sup_digit):
    total = 0
    for number in sup_digit:
        total += int(number)
    return str(total)

# Complete the superDigit function below.
def superDigit(n, k):
    sup_digit = sum_digit(n)*k
    # base case
    if len(sup_digit) == 1:
        return str(sup_digit) 
    
    else:
        return str(superDigit(sup_digit, 1))

Which works as well so I guess the problem was not the sum_digit function but summing n then multiplying by k rather than n*k then summing all numbers.