letter combinations of a phone number

来源:互联网 发布:大数据成熟度模型 编辑:程序博客网 时间:2024/05/29 17:44
# -*- coding: utf-8 -*-'''lambda:匿名函数   lambda 参数 :表达式reduce(function, sequence[, initial]) -> value        Apply a function of two arguments cumulatively to the items of a sequence,    from left to right, so as to reduce the sequence to a single value.    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items    of the sequence in the calculation, and serves as a default when the    sequence is empty.'''class Solution(object):    def letterCombinations(self, digits):        """        :type digits: str        :rtype: List[str]        """        mapping={'1':' ','2':'abc','3':'def','4':'ghi','5':'jkl',                  '6':'mno','7':'pgrs','8':'tuv','9':'wxyz'}        if len(digits)==0:            return []        if len(digits)==1:        return list(mapping[digits[0]])        pre = self.letterCombinations(digits[:-1])        additional = mapping[digits[-1]]        return [s + c for s in pre for c in additional]    def letterCombinations2(self, digits):        if '' == digits: return []        kvmaps = {            '2': 'abc',            '3': 'def',            '4': 'ghi',            '5': 'jkl',            '6': 'mno',            '7': 'pqrs',            '8': 'tuv',            '9': 'wxyz'        }        return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])mydigits=Solution()d= mydigits.letterCombinations2('23')print d