Loading distances.py +40 −30 Original line number Diff line number Diff line Loading @@ -2,37 +2,47 @@ import sys import random as rand from time import time import Levenshtein as leven def rperm(l): d = len(l) class Robustness: def __init__(self, filename): self.l = list() with open(filename) as inbuff: for word in inbuff: word = word.strip() self.l.append(word) self.distance = leven.distance self.k = len(self.l) self.algo = self.rperm def rperm(self): d = len(self.l) for i in range(d): r = rand.randint(i, d-1) l[i], l[r] = l[r], l[i] yield l[i] self.l[i], self.l[r] = self.l[r], self.l[i] yield self.l[i] def cost(l): def cost_rate(self): c = 0 perm = rperm(l) k = self.k ratio = len(self.l) / self.k perm = self.algo() w0 = next(perm) for w in perm: c += leven.distance(w0, w) c += self.distance(w0, w) w0 = w return c if k == 0: break k -= 1 return int(c * ratio) l = list() filename = sys.argv[1] a = time() with open(filename) as inbuff: for word in inbuff: word = word.strip() l.append(word) min_c = cost(l) for i in range(19): before = time() c = cost(l) after = time() print(c, after-before) min_c = min(c, min_c) print(min_c) No newline at end of file def min_rperm(self, n=1): min_c = self.cost_rate() for i in range(n-1): min_c = min(min_c, self.cost_rate()) return min_c if __name__ == '__main__': R = Robustness(sys.argv[1]) R.k = int(len(R.l)/5) print(R.min_rperm(n=10)) No newline at end of file Loading
distances.py +40 −30 Original line number Diff line number Diff line Loading @@ -2,37 +2,47 @@ import sys import random as rand from time import time import Levenshtein as leven def rperm(l): d = len(l) class Robustness: def __init__(self, filename): self.l = list() with open(filename) as inbuff: for word in inbuff: word = word.strip() self.l.append(word) self.distance = leven.distance self.k = len(self.l) self.algo = self.rperm def rperm(self): d = len(self.l) for i in range(d): r = rand.randint(i, d-1) l[i], l[r] = l[r], l[i] yield l[i] self.l[i], self.l[r] = self.l[r], self.l[i] yield self.l[i] def cost(l): def cost_rate(self): c = 0 perm = rperm(l) k = self.k ratio = len(self.l) / self.k perm = self.algo() w0 = next(perm) for w in perm: c += leven.distance(w0, w) c += self.distance(w0, w) w0 = w return c if k == 0: break k -= 1 return int(c * ratio) l = list() filename = sys.argv[1] a = time() with open(filename) as inbuff: for word in inbuff: word = word.strip() l.append(word) min_c = cost(l) for i in range(19): before = time() c = cost(l) after = time() print(c, after-before) min_c = min(c, min_c) print(min_c) No newline at end of file def min_rperm(self, n=1): min_c = self.cost_rate() for i in range(n-1): min_c = min(min_c, self.cost_rate()) return min_c if __name__ == '__main__': R = Robustness(sys.argv[1]) R.k = int(len(R.l)/5) print(R.min_rperm(n=10)) No newline at end of file