昨天,我正在做一個問題,我必須完成一個功能,該功能可以在輸入文字后將電話號碼轉換為數字,我曾經s.replace()
這樣做過,還有修飾符。由于這個問題存在于hackerrank問題中,我無法提供完整的代碼,因為測驗已經結束并且頁面不再可用。我該如何使用這些修飾符,例如“二三四雙二三三”將列印 23422333?
def getPhoneNumber(s):
s.replace("Zero" "0")
s.replace("one" "1")
...
modifier = {
"double": 2,
"triple" : 3,
}
uj5u.com熱心網友回復:
d = {'zero':'0','one':'1','two':'2','three':'3','four':'4','five':'5','six':'6','seven':'7','eight':'8','nine':'9'}
mod = {'double':2,'triple':3}
num_word = input('Enter Number In Words').split(' ')
number = ''
m = 1
for a in num_word:
try:
m = mod[a.lower()]
continue
except KeyError:
pass
try:
number =d[a.lower()]*m
m = 1
except KeyError:
number =a.lower()*m
m = 1
print(number)
輸出
IN: double two
OUT: 22
IN: two three four double two triple 3
OUT: 23422333
uj5u.com熱心網友回復:
試試這個,
def getPhoneNumber(number):
to_replace = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}
modifiers = {"double":2, "triple":3}
words = list(map(str.lower, number.split()))
output = ""
skip = None
for index, word in enumerate(words):
if index == skip:
continue
if word in modifiers:
skip = index 1
try:
output = modifiers[word] * to_replace[words[skip]]
except:
pass
else:
output = to_replace[word]
return output
getPhoneNumber("Double One Triple Two Five")
輸出 -
112225
uj5u.com熱心網友回復:
numbers = {'zero':'0','one':'1','two':'2','three':'3','four':'4','five':'5','six':'6','seven':'7','eight':'8','nine':'9'}
multipliers = {'double':2,'triple':3}
def solve(sentence):
results = []
sentence = sentence.lower().split()
repeat = 1
for word in sentence:
if word in multipliers:
repeat = multipliers[word]
else:
if word in numbers:
word = numbers[word]
results.append(word * repeat)
repeat = 1
return ''.join(results)
uj5u.com熱心網友回復:
我將把它作為其他主題的變體扔在那里:
d = {'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4',
'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'}
mod = {'double': 2, 'triple': 3}
num_word = input('Enter Number In Words: ')
number = []
m = None
for word in map(str.lower, num_word.split()):
if m:
number.extend(d.get(word, '') * m)
m = None
else:
if not (m := mod.get(word)):
number.append(d.get(word))
print(''.join(filter(bool, number)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/470913.html
標籤:Python python-2.7