Skip to content

Instantly share code, notes, and snippets.

@margnus1
Last active December 12, 2015 09:49
Show Gist options
  • Select an option

  • Save margnus1/4754090 to your computer and use it in GitHub Desktop.

Select an option

Save margnus1/4754090 to your computer and use it in GitHub Desktop.
Tester för AD2.Ass2.1. Now with randomly generated tests!
#!/usr/bin/env python2.7
from __future__ import print_function
from min_difference import *
from string import ascii_lowercase
import random
def defvalf(a, b):
return 0 if a==b else 1
def makeR(firstAlpha, secondAlpha, valf=defvalf):
return dict([(a, dict([(b, valf(a, b))
for b in secondAlpha]))
for a in firstAlpha])
lc = ascii_lowercase + '-'
lcR = makeR(lc, lc)
ok = fail = 0
def isSubsequence(subs, lst):
if len(subs) == 0: return True
if len(lst) == 0: return False
if subs[0] == lst[0]:
return isSubsequence(subs[1:], lst[1:])
else:
return isSubsequence(subs, lst[1:])
def test(x, y, dist, R=lcR):
global ok
global fail
result = min_difference(x, y, R)
if dist != result:
print ("min_diff error")
print ("Expected", dist, "got", result)
print ("For x =", x, ", y = ", y)
fail += 1
else:
ok += 1
oldx, oldy = x, y
result = d, x, y = min_difference_align(x, y, R)
calculatedDist = sum(map((lambda (x, y) : R[x][y]), zip(x, y)))
if len(x) != len(y) or calculatedDist != d or d != dist or not(isSubsequence(oldx, x)) or not(isSubsequence(oldy, y)):
print ("min_diff_align(x,y,R) error")
print ("For x =", oldx, ", y = ", oldy)
if d != dist: print ("Expected difference", dist, ", got", d)
if len(x) != len(y): print ("The alignments are of different lengths")
if calculatedDist != d:
print ("The alignment has distance", calculatedDist,
"but the dist", d, "was returned")
if not(isSubsequence(oldx, x)): print ("x is not a subseq of", x)
if not(isSubsequence(oldy, y)): print ("y is not a subseq of", y)
fail += 1
else:
ok += 1
def random_string(alphabet=ascii_lowercase, maxlen=20):
l = random.randint(0, maxlen)
return ''.join([random.choice(alphabet) for _i in range(l)])
def random_test():
x = random_string()
y = random_string()
R = lcR
dist = min_difference(x, y, R)
test(x, y, dist, R)
R = makeR(x + '-', y + '-')
dist = min_difference(x, y, R)
test(x, y, dist, R)
R = makeR(x + '-', y + '-', lambda a,b: random.randint(0, 100))
dist = min_difference(x, y, R)
test(x, y, dist, R)
def test_randomly():
for _i in range(10000):
random_test()
test("dinamck", "dynamic", 3)
test("dinamck", "dynamic", 3, makeR("dinamck-", "dynamic-"))
test("", "lololololabc", 12)
test("ahejsan", "hejsanb", 2)
test("gurka", "gurka", 0)
test("", "", 0)
test("bakis", "", 5)
test_randomly()
print ("Failed:", fail, "Passed:", ok)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment