2018年2月24日 星期六

[ Python 常見問題 ] unfold function in python

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: 
>>> def fromDigits(digits): 
... return reduce(lambda x, y: 10 * x + y, digits, 0) 
... 
>>> fromDigits([1, 2, 3]) 
123

Now I want to implement the reverse function: 
  1. def toDigits(num):  
  2.    return unfold(lambda m,digits: (m/10,digits+[m % 10]) if m>0 else None,  num,  [])  
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: 
  1. def to_digits(x):  
  2.     if not x: return []  
  3.     return to_digits(x//10) + [x%10]  
  4.   
  5. to_digits(12345)  


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...