如何修改以下程序,以确保它替换的每个字母都是唯一的?

时间:2013-11-20 20:46:17

标签: python string random

我写了一个程序,它带有一个3个字母的字符串列表(也称为密码子,对于那些了解生物学的人),对于每个字符串,它将选择3个字母中的任意一个(随机)并将用A,G,C或T(随机)。例如:对于字符串GCT,它将随机选择3个位置中的任意一个,即C,然后它会随机将其更改为A,G,C或T即T.所以新字符串(或密码子)生成的将是GTT,依此类推列表中的下一个字符串。

然而,有一个问题。我编写它的方式不会检查以确保它生成的新字符串与旧字符串不同。因此,如果程序随机选择将字母更改为与初始相同的字母,则它将偶然输出相同的字符串,即再次将C从GCT切换为C并生成GCT。我想确保这不会发生,因此程序不会生成相同的字符串,因为在分析数十万个密码子/字符串时,这确实是偶然发生的。我试图通过在我的'for'循环的第二行使用list(A,G,T,C) - 密码子[index]来做到这一点,但它没有用。

我不会打扰你的整个代码,但最初我只是打开了我的密码子/字符串列在其中的文件(在一列中)并将它们全部附加到一个列表中并将其命名为'codon'。这是剩下的部分:

import random 
def string_replace(s,index,char):
return s[:index] + char + s[index+1:]

for x in range(1,10):   # I set the range to 10 so that I can manually check if the program worked properly 
    index = random.randrange(3)
    letter_to_replace = random.choice(list({"A", "G", "T", "C"} - {codon[index]}))
    mutated_codon = [string_replace(codon[x], index, letter_to_replace)]   
    print mutated_codon) 

5 个答案:

答案 0 :(得分:2)

- {codon[index] 

- >如果密码子是3个字母的字符串列表,这将是3个字母的代码 认为你想要密码子[x] [索引]

答案 1 :(得分:1)

编辑功能,让你的密码组在那里,而不是向下,给索引替换那里, 我不知道你将如何创建密码子列表,但这里我有一个例子

listofcodons=["ATC", "AGT", "ACC"]
for s in listofcodons:
    index=random.randrange(3)
    mutated=string_replace(s,index)
    print mutated


def string_replace(s,index):
        codonset=set(["A","C","G","T"])
        toreplace=s[index]
        #codonset.pop(toreplace)
        codonset.remove(toreplace)            
        char=random.choice(codonset)
        return s[:index] + char + s[index+1:]

答案 2 :(得分:1)

所以我很无聊并且决定将它编码为高尔夫球(可能会更短但在这里很满意)。

from random import choice as c
a=['ACT','ATT','GCT'] # as many as you want
f=lambda s,i:s[:i]+c(list(set(['A','G','C','T'])-set(s[i])))+s[i+1:]
b=[f(s,c([0,1,2]))for s in a]
print b

a可以是您的密码子列表,b将是一个随机索引替换为随机(从不相同)字母的密码子列表。

好的回答你的新问题:

from random import choice as c
codons = ['ACT','ATT','GCT']
f=lambda s,i:s[:i]+c(list(set(['A','G','C','T'])-set(s[i])))+s[i+1:]
mutated_codons = [f(s,c([0,1,2]))for s in codons]

for codon in mutated_codons:
try:
    print codon, codon_lookup[codon]
except KeyError, e:
    print e

假设您的词典被称为condon_lookup,这将打印每个突变密码子,然后进行氨基酸查找。您的旧代码循环遍历每个突变密码子中的字母,而不是像您预期的那样循环显示密码子列表。

答案 3 :(得分:0)

您可以使用while循环:

import random

mutated_codon=codon='GCT'

while mutated_codon==codon:
    li=list(mutated_codon)
    li[random.choice([0,1,2])]=random.choice(["A", "G", "T", "C"]) 
    mutated_codon = ''.join(li) 

print codon, mutated_codon     

答案 4 :(得分:0)

这样的事情怎么样?

#!/usr/local/cpython-3.3/bin/python

import random

def yield_mutated_codons(codon):
    possible_set = set({"A", "G", "T", "C"})

    for x in range(1, 10):
        index = random.randrange(3)
        letter_to_replace = codon[index]
        current_set = possible_set - set(letter_to_replace)
        codon[index] = random.choice(list(current_set))
        yield ''.join(codon)

def main():
    codon = list('GAT')

    for mutated_codon in yield_mutated_codons(codon):
        print(mutated_codon)

main()