我怎样才能打印出所有可能的字母组合一个给定的电话号码能重新present? [英] How can I print out all possible letter combinations a given phone number can represent?

查看:189
本文介绍了我怎样才能打印出所有可能的字母组合一个给定的电话号码能重新present?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想为我的第一个编程面试的问题之一是写给定一个7位数的电话号码的程序,可以打印信件,每个号码可以重新present所有可能的组合。

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 of letters that each number could represent.

这个问题的第二部分是像什么样,如果这将是一个12位的国际号码?如何将这种影响您的设计。

A second part of the question was like what about if this would have been a 12 digit international number? How would that effect your design.

我没有code,我在采访中写道,但我得到了IM pression他不喜欢它。
什么是做到这一点的最好方法是什么?

I don't have the code that I wrote in the interview, but I got the impression he wasn't happy with it.
What is the best way to do this?

推荐答案

在Python中,迭代:

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 是一个结果列表为止;最初它填充了一个项目,空字符串。然后,在输入字符串中的每个字符,它查找的从顶部所限定的字典与之匹配的字母列表。然后,它取代了名单 RET 与现有的preFIX和可能的字母组合,每

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.

这篇关于我怎样才能打印出所有可能的字母组合一个给定的电话号码能重新present?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆