【发布时间】:2013-12-10 10:09:13
【问题描述】:
这是一个家庭作业,我解决了这个问题,但我正在尝试找到一个更快的解决方案。
问题如下:我需要弄清楚有多少个可能的氨基酸(aa)序列存在总质量为 m。 我有一张氨基酸表(单字母字符串)和它们对应的质量(int),我把它放在字典里。
我最初的解决方案是创建 aa 的所有可能组合,并将每个组合的总质量与质量 m 进行比较。这适用于少量的 m,但是当 m 开始达到数百个时,组合的数量会变得非常高。
我做了一些小的优化,让它在 m
这是我目前所拥有的:
totalmass = m
def pepList():
tempList = ['']
temp2List = []
length = 0
total = 0
aminoList = 'GASPVTCINDKEMHFRYW' #this are all the aminoacids
while length < maxLength:
for i in tempList:
for j in aminoList:
pepMass = peptideMass(i+j, massTable) #find the mass of
#this peptide
if pepMass == totalmass:
total += 1
elif pepMass <= totalmass:
temp2List.append(i+j)
tempList = []
for i in temp2List:
tempList.append(i)
temp2List = []
length = length + 1
print (total)
pepList()
我可以在大约一秒内得到 m = 300 的解,但 m = 500 大约需要 40 秒
我尝试了使用 itertools 的替代方法,但速度并不快:
total = 0
pepList = []
for i in range(maxLength+1):
for p in itertools.combinations_with_replacement(aminoList, i):
#order matters for the total number of peptides but not for calculating
#the total mass
amino = ''.join(p)
if peptideMass(amino, massTable) == mass:
pepList.append(amino)
print (len(pepList))
newpepList = []
for i in pepList:
for p in itertools.permutations(i, r = len(i)):
#I use permutations here to get the total number because order matters
if p not in newpepList:
newpepList.append(p)
total +=1
print (total)
示例输入: 米 = 270 输出: 22
【问题讨论】:
-
欢迎来到 StackOverflow,您的问题很好 - 您提供了很好的解释和代码,但是,如果您可以提供一些示例输入和输出以便其他用户可以检查以确保他们为您提供了一个好的和正确的解决方案。无论如何,存在一个小问题 - 您的问题对您的项目和问题非常具体,因此适用于每个人,为了更好地获得帮助,请尝试提出更通用的问题,可能专注于代码的某个方面,并请求帮助在一个新问题中对其进行优化。
-
谢谢。另一个问题似乎是完全相同的问题,所以我会检查一下。
标签: python optimization python-3.x bioinformatics