date posted: 2020-05-01
For those of you who do not know what recursive algorithm, reading this will help --> What is Recursive algorithm
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))
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))
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
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.