我偶然发现了一个超出我技能水平的问题
找到任何提供的化学式的唯一原子及其计数,如K4(ON(SO3)2)2。-我的要求就在这里
我发现这个问题可能需要递归和/或动态编程(或至少有用)
以下是我取得的成绩:
class Solution(object):
def __init__(self):
self.code = []
self.atoms = {}
def encode_string(self,string):
"""
Return a list of elements where
@'a' = alphabetical
@'d' = digit
@int = parentheses, wherre number reflects nesting.
'k4(on(so3)2)2' --> ['a', 'd', 1, 'a', 'a', 2, 'a', 'a', 'd', 2, 'd', 1, 'd']
"""
self.string = string
for char in string:
if char.isalpha():
self.code.append('a')
elif char.isdigit():
self.code.append('d')
elif char == '(':
self.code.append('l') #left parenthesis
else:
self.code.append('r') #right parenthesis
self.pars = [elem for elem in self.code if elem in ['r','l']]
self.par_structure = []
count = 1
for idx, elem in enumerate(self.pars):
if elem == 'l':
self.par_structure.append(count)
count += 1
elif elem == 'r':
count -= 1
self.par_structure.append(count)
count = 0
for idx, char in enumerate(self.code):
if char in ['l','r']:
self.code[idx] = self.par_structure[count]
count += 1
def id_atoms(self):
self.indices = [idx for idx,elem in enumerate(self.code) if elem == 0]
for idx in self.indices:
atom = self.string[idx]
self.atoms[atom] = 0
def parse_code():
pass
我列出了encode_string方法的用例,该方法通过字母、数字和括号的深度级别来识别字母、数字和括号。我认为这是朝着解决问题的方向取得的进展。下一步是将括号内的字符乘以找到的数字值
任何建议都将不胜感激
下面是我将如何着手解决上述问题。我假设原子以大写字母('H')开头,后面可能是小写字母('Mg'):
对于格式错误的字符串,代码并不健壮,我将此作为练习留给读者。我希望您能在代码中找到一些有用的想法
输出
另一次尝试:
印刷品:
这个问题来自726. Number of Atoms
基于aJava Solution on Github to Python平移的算法
测试
使用来自726. Number of Atoms的测试用例
输出
相关问题 更多 >
编程相关推荐