我正在尝试生成一个带有 6 个 UNIQUE 条码的随机条码列表,这些条码的汉明距离为 3。问题是程序正在生成一个带有重复的条码列表,而不是正确的汉明距离。下面是代码。
import random
nucl_list = ['A', 'C', 'G', 'T']
length = 6
number = 6
attempts = 1000
barcode_list = []
tested = []
def make_barcode():
"""Generates a random barcode from nucl_list"""
barcode = ''
for i in range(length):
barcode += random.choice(nucl_list)
return barcode
def distance(s1, s2):
"""Calculates the hamming distance between s1 and s2"""
length1 = len(s1)
length2 = len(s2)
# Initiate 2-D array
distances = [[0 for i in range(length2 + 1)] for j in range(length1 + 1)]
# Add in null values for the x rows and y columns
for i in range(0, length1 + 1):
distances[i][0] = i
for j in range(0, length2 + 1):
distances[0][j] = j
for i in range(1, length1 + 1):
for j in range(1,length2 + 1):
cost = 0
if s1[i - 1] != s2[j - 1]:
cost = 1
distances[i][j] = min(distances[i - 1][j - 1] + cost, distances[i][j - 1] + 1, distances[i - 1][j] + 1)
min_distance = distances[length1][length2]
for i in range(0, length1 + 1):
min_distance = min(min_distance, distances[i][length2])
for j in range(0, length2 + 1):
min_distance = min(min_distance, distances[length1][j])
return min_distance
def compare_barcodes():
"""Generates a new barcode and compares with barcodes in barcode_list"""
new_barcode = make_barcode()
# keep track of # of barcodes tested
tested.append(new_barcode)
if new_barcode not in barcode_list:
for barcode in barcode_list:
dist = distance(barcode, new_barcode)
if dist >= 3:
barcode_list.append(new_barcode)
else:
pass
else:
pass
# make first barcode
first_barc = ''
for i in xrange(length):
first_barc += random.choice(nucl_list)
barcode_list.append(first_barc)
while len(tested) < attempts:
if len(barcode_list) < number:
compare_barcodes()
else:
break
barcode_list.sort()
print barcode_list
我认为我的问题在于最后一个 while 循环:我想compare_barcodes
不断生成符合条件的条形码(不是重复的,并且不在已经生成的任何条形码的汉明距离内)。