0
How do I write a high order function that accepts a function (like the ones below) and an integer?
So it is a function that accepts a function and an integer as arguments. Depending on the function argument, digits will either return either the sum or count of the digits of the integer argument. Example: >>> digits(f,245) 11 >>> digits(g,245) 3 def sum_digits(x): if x < 10: return x else: all_but_last, last = x // 10, x % 10 return sum_digits(all_but_last) + last def count_digits(x): if x < 10: return 1 else: return 1 + count_digits(x / 10)
2 Respuestas
+ 1
def digits(func, number):
if number < 10:
return func(number)
return digits(func, number//10)+func(number%10)