Source From Here
Question
I have started practicing functional programming in python recently. Lets say I define a function that gets an array of digits and concatenates it:
Now I want to implement the reverse function:
But I couldn't find a definition of
unfold in the python functools or anywhere in the standard library.
How-To
unfold is not a python function ... here is a recursive solution:
Question
I have started practicing functional programming in python recently. Lets say I define a function that gets an array of digits and concatenates it:
Now I want to implement the reverse function:
- def toDigits(num):
- return unfold(lambda m,digits: (m/10,digits+[m % 10]) if m>0 else None, num, [])
How-To
unfold is not a python function ... here is a recursive solution:
- def to_digits(x):
- if not x: return []
- return to_digits(x//10) + [x%10]
- to_digits(12345)
沒有留言:
張貼留言