How can I print out all possible letter combinations a given phone number can represent?

前端 未结 30 2174
逝去的感伤
逝去的感伤 2020-12-22 18:01

I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations

30条回答
  •  [愿得一人]
    2020-12-22 18:55

    In Python, iterative:

    digit_map = {
        '2': 'abc',
        '3': 'def',
        '4': 'ghi',
        '5': 'jkl',
        '6': 'mno',
        '7': 'pqrs',
        '8': 'tuv',
        '9': 'wxyz',
    }
    
    def word_numbers(input):
      input = str(input)
      ret = ['']
      for char in input:
        letters = digit_map.get(char, '')
        ret = [prefix+letter for prefix in ret for letter in letters]
      return ret
    

    ret is a list of results so far; initially it is populated with one item, the empty string. Then, for each character in the input string, it looks up the list of letters that match it from the dict defined at the top. It then replaces the list ret with the every combination of existing prefix and possible letter.

提交回复
热议问题