我需要创建一个接收一串数字的函数,而输出是与这些数字相对应的字母,就像你在手机上发送消息一样。例如,要获得字母“A'输入应该是' 2',以获得字母' B'输入应该是' 22'等等。例如:
>>>number_to_word('222 '233' '3'):
"CAFE"
该计划需要"四处走动"如果达到数量限制,则为数字。例如,字母“A'”可以是以下输入:' 2',' 2222',' 2222222'等等。就像你在通过手机时发送短信一样,C' (这是' 222')该节目再次进入' A'制作' 2222'这是关键。此外,在输入中,如果字符串是' 233'该计划必须将不同的数字分开,因此(' 233')将与此相同(' 2'' 33') 我做了一个这样的字典:
dic={'2':'A', '22':'B', '222':'C', '3':'D', '33':'E', '333':'F',..... etc}
但是我不知道如何制作节目"四处走走"如果输入是' 2222',我该如何取出该号码并将其分配给字母' A'。 如果您不理解我的问题,请随时提出任何问题。我很乐意更详细地解释一下。谢谢。
答案 0 :(得分:0)
这似乎给出了预期的结果:
NUMBERS = {'2': 'A', '22': 'B', '222': 'C', '3': 'D', '33':'E', '333': 'F'}
def normalize_number(number):
for item in number.split():
if len(set(item)) == 1:
yield item
else:
last = item[0]
res = [last]
for entry in item[1:]:
if entry == last:
res.append(entry)
else:
yield ''.join(res)
res = [entry]
last = entry
yield ''.join(res)
def number_to_word(number):
res = []
for item in normalize_number(number):
try:
res.append(NUMBERS[item])
except KeyError:
if len(item) >= 4:
end = len(item) % 3
if end == 0:
end = 3
res.append(NUMBERS[item[:end]])
return ''.join(res)
测试它:
>>> number_to_word('222 2 333 33')
'CAFE'
>>> number_to_word('222 2 333 3333')
'CAFE'
>>> number_to_word('222 2 333 333333')
'CAFE'
>>> number_to_word('222 2333 3333')
'CAFE'
函数normalize_number()
将具有不同数字的数字转换为只有相同数字的多个数字:
>>> list(normalize_number('222 2 333 3333'))
['222', '2', '333', '3333']
>>> list(normalize_number('222 2333 3333'))
['222', '2', '333', '3333']
>>> list(normalize_number('222 2 333 53333'))
['222', '2', '333', '5', '3333']