4 回答
TA贡献1875条经验 获得超5个赞
你可以尝试做这样的事情:
def number_to_letter(encoded):
result = ""
buffer = ""
for ch in encoded:
if ch == '-':
if buffer and 0 < int(buffer) < 27:
result += chr(64 + int(buffer))
buffer = ""
elif ch.isdigit():
buffer += ch
else:
if buffer and 0 < int(buffer) < 27:
result += chr(64 + int(buffer))
return result
print(number_to_letter('1-3-5'))
输出:
ACE
解释:
我们循环每个字符并将其添加到某个缓冲区中。当我们遇到-(分隔符)时,我们尝试解析缓冲区并重置它。最后我们再进行一次相同的解析并返回结果。
验证的工作方式是,每当我们填充缓冲区时,我们都会检查数字有效性(使用.isdigit()),并且当我们解析缓冲区时,我们会检查范围约束。
TA贡献1798条经验 获得超7个赞
没有清单,好吧。但是听写呢?
def abc(nums):
d = {'-':'','1':'A','2':'B','3':'C','4':'D','5':'E','6':'F','7':'G','8':'H','9':'I','0':'J'}
res = ''
for n in nums: res += d[n]
return res
print(abc('1-2-3-9-0')) # Output: ABCIJ
这是一个更正的版本:
def abc(nums):
d = {'-':'','1':'A','2':'B','3':'C','4':'D','5':'E','6':'F','7':'G','8':'H','9':'I','0':'J'}
res = ''
for n in nums:
if n in d:
res += d[n]
return res
print(abc('?-2-3-9-0')) # Output: BCIJ
TA贡献1854条经验 获得超8个赞
这段代码的方法是找到第一个“-”,然后将其存储在哪里,这样下次我们就可以在最后一个“-”之后查找第一个“-”
当我的代码中的注释谈论循环时意味着要经历一次循环(循环时:)
def number_to_letter(encoded):
letterString = ""
startSubStr = 0
endSubStr = 0
looping = True
while looping:
if endSubStr > (len(encoded)-4):# if we're at the last number we don't look for '-'. we go to the end of the str and end the loop
endSubStr = len(encoded)
looping = False
else:
endSubStr = encoded.index('-', startSubStr) #find the first '-' after the '-' found in the last cycle
number = int(encoded[startSubStr:endSubStr]) #get the number between the '-' found in the last cycle through this loop and the '-' found in this one
if number < 27:
letter = chr(64 + int(number))
letterString += letter
startSubStr = endSubStr + 1 #set the start of the substring to the end so the index function doesn't find the '-' found in this cycle again
return letterString
print(number_to_letter("23-1-1-2")) #>>> WAAB
结果:WAAB
TA贡献1812条经验 获得超5个赞
import string
alphabet = list(string.ascii_lowercase)
combination = "1-2-3"
def seperate(s, sep='-'):
return [s[:s.index(sep)]] + seperate(s[s.index(sep)+1:]) if sep in s else [s]
combination = seperate(combination)
print("".join([alphabet[int(i)-1] for i in combination]))
添加回答
举报