from random import randint
def replace_base_randomly_using_names(base_seq):
"""Return a sequence with the base at a randomly selected position of base_seq
replaced by a base chosen randomly from the three bases that are not at that
position."""
position = randint(0, len(base_seq) - 1) # −1 because len is one past end
base = base_seq[position]
bases = 'TCAG'
bases.replace(base, '') # replace with empty string!
newbase = bases[randint(0,2)]
beginning = base_seq[0:position] # up to position
end = base_seq[position+1:] # omitting the base at position
return beginning + newbase + end
这应该模拟一个突变。我不明白如何选择不同的基础(来自TCAG内部)以确保基础确实改变,正如doctype所提到的那样。
编辑:
上述代码的另一个版本执行相同的操作:
def replace_base_randomly(base_seq):
position = randint(0, len(base_seq) - 1)
bases = 'TCAG'.replace(base_seq[position], '')
return (base_seq[0:position] +
bases [randint(0,2)] +
base_seq[position+1:])
要明确的是,我的问题是如何用不同的基础替换基础?
答案 0 :(得分:1)
考虑将print语句交错到代码中,你可以看到它正在做什么。这是算法:
它不会编辑字符串 - 它会从旧字符串的两个部分再加上新的字符串创建一个新字符串,然后返回该字符串。
答案 1 :(得分:0)
字符串在python中是不可变的,您应该将从bases.replace(base, '')
返回的字符串重新分配给bases
。
bases = bases.replace(base, '')
答案 2 :(得分:0)
行bases.replace(base, '')
实际上并未更改bases
字符串。要更改bases
字符串,您必须设置bases = bases.replace(base, '')
。自己测试
bases = 'ACGT'
base = 'A'
print bases #prints 'ACGT'
bases.replace(base, '')
print bases #prints 'ACGT'
bases = bases.replace(base, '')
print bases #prints 'CGT'
从这里开始,现在可能的碱基列表已经减少到只有突变的碱基,该函数随机选择一个带bases[randint(0, 2)]
的碱基并将其附加到新序列。