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)

6th Apr 2017, 2:35 AM
Tafari Johnson
Tafari Johnson - avatar
2 ответов
+ 1
def digits(func, number): if number < 10: return func(number) return digits(func, number//10)+func(number%10)
8th Apr 2017, 6:45 PM
Tafari Johnson
Tafari Johnson - avatar
3rd Apr 2017, 7:01 PM
Luca Garrera