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]))
添加回答
舉報