所以我试图解决这个leetcode问题:
输入:命令=“ G()(al)”
输出:“目标”
说明:Goal Parser对命令的解释如下:
G-> G
()-> o
(al)-> al
最终的连接结果是“目标”。
这是我的代码:
def interpret(command: str) -> str:
res = ''
for i in command:
if i == 'G':
res += i
if i == '(':
ind = command.index(i)
if command[ind + 1] == ')':
res += 'o'
if command[ind + 1] == 'a':
res += 'al'
return res
问题是,该函数返回了“ Goo”,而不是返回“ Goal”。因此,我将函数更改为以下内容以查看发生了什么:
for i in command:
if i == '(':
print(command.index(i))
上面的代码打印出了这个
1
1
这意味着循环将元素重复两次?
我做错了什么,如何修复该函数以返回正确的输出?
command.index()
给您第一次出现的'('。
重写您的函数,如下所示:
def interpret(command: str) -> str:
res = ""
for c, i in enumerate(command):
if i == "G":
res += i
if i == "(":
ind = c
if command[ind + 1] == ")":
res += "o"
if command[ind + 1] == "a":
res += "al"
return res
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句