简体   繁体   English

将长数字转换为对应的字母组合

[英]Convert a long number to corresponding letter combinations

Given a number, translate it to all possible combinations of corresponding letters.给定一个数字,将其转换为相应字母的所有可能组合。 For example, if given the number 1234 , it should spit out abcd , lcd , and awd because the combinations of numbers corresponding to letters could be 1 2 3 4 , 12 3 4 , or 1 23 4 .例如,如果给定数字1234 ,它应该吐出abcdlcdawd因为与字母对应的数字组合可能是1 2 3 412 3 41 23 4

I was thinking of ways to do this in Python and I was honestly stumped.我正在考虑在 Python 中执行此操作的方法,老实说我被难住了。 Any hints?任何提示?

I basically only setup a simple system to convert single digit to letters so far.到目前为止,我基本上只设置了一个简单的系统来将单个数字转换为字母。

Make str .制作str

Implement partition as in here .这里实现分区

Filter lists with a number over 26.过滤数字超过 26 的列表。

Write function that returns letters.编写返回字母的函数。

def alphabet(n):
    # return " abcde..."[n]
    return chr(n + 96)


def partition(lst):
    for i in range(1, len(lst)):
        for r in partition(lst[i:]):
            yield [lst[:i]] + r
    yield [lst]


def int2words(x):
    for lst in partition(str(x)):
        ints = [int(i) for i in lst]
        if all(i <= 26 for i in ints):
            yield "".join(alphabet(i) for i in ints)


x = 12121
print(list(int2words(x)))
# ['ababa', 'abau', 'abla', 'auba', 'auu', 'laba', 'lau', 'lla']

I'm not gonna give you a complete solution but an idea where to start:我不会给你一个完整的解决方案,而是一个从哪里开始的想法:

I would transform the number to a string and iterate over the string, as the alphabet has 26 characters you would only have to check one- and two-digit numbers.我会将数字转换为字符串并遍历字符串,因为字母表有 26 个字符,因此您只需检查一位和两位数字。

As in a comment above a recursive approach will do the trick, eg:正如上面的评论一样,递归方法可以解决问题,例如:

Number is 1234号码是 1234

*) Take first character -> number is 1 *) 取第一个字符 -> 数字为 1

*) From there combine it with all remaining 1-digit numbers --> *) 从那里将它与所有剩余的 1 位数字结合 -->

      1 2 3 4

*) Then combine it with the next 2 digit number (if <= 26) and the remaining 1 digit numbers --> *) 然后将其与下一个 2 位数字(如果 <= 26)和剩余的 1 位数字组合 -->

      1 23 4

*) ...and so on *) ...等等

As i said, it's just an idea where to start, but basically its a recursive approach using combinatorics including checks if two digit numbers aren't greater then 26 and thus beyond the alphabet.正如我所说,这只是一个从哪里开始的想法,但基本上它是一种使用组合学的递归方法,包括检查两位数字是否不大于 26,从而超出字母表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM