Advertisement
Guest User

dp

a guest
May 22nd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. # dynamic programming
  2. # LCS                   22.05.17
  3.  
  4. import timeit
  5.  
  6. #sampleString1 = "abcdefgjoopf"
  7. #sampleString2 = "abcjjahf"
  8. sampleString1 = "thisisatest"
  9. sampleString2 = "testing123testing"
  10. # sampleString1 = "ABCBDAB"
  11. # sampleString2 = "BDCABA"
  12. # sampleString1 = "XMJYAUZ"
  13. # sampleString2 = "MZJAWXU"
  14.  
  15. def lcsRecursive(X, Y):
  16.     if not X or not Y:
  17.        return ""
  18.     x, Xs, y, Ys = X[0], X[1:], Y[0], Y[1:]
  19.     if x == y:
  20.        return x + lcsRecursive(Xs, Ys)
  21.     else:
  22.        return max(lcsRecursive(X, Ys), lcsRecursive(Xs, Y), key=len)
  23.        
  24. def lcsDP(X, Y):
  25.     lengths = [[0 for j in range(len(Y)+1)] for i in range(len(X)+1)]
  26.    
  27.     for i, x in enumerate(X):
  28.         for j, y in enumerate(Y):
  29.             if x == y:
  30.                 lengths[i+1][j+1] = lengths[i][j] + 1
  31.             else:
  32.                 lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])
  33.    
  34.     result = ""
  35.     x, y = len(X), len(Y)
  36.     while x != 0 and y != 0:
  37.         if lengths[x][y] == lengths[x-1][y]:
  38.             x -= 1
  39.         elif lengths[x][y] == lengths[x][y-1]:
  40.             y -= 1
  41.         else:
  42.             assert X[x-1] == Y[y-1]
  43.             result = X[x-1] + result
  44.             x -= 1
  45.             y -= 1
  46.     return result
  47.  
  48. dptime = timeit.default_timer()
  49. dpLCS = lcsDP(sampleString1, sampleString2)
  50. dptime = timeit.default_timer() - dptime
  51.  
  52. rectime = timeit.default_timer()
  53. recLCS = lcsRecursive(sampleString1, sampleString2)
  54. rectime = timeit.default_timer() - rectime
  55.  
  56.  
  57. print("String1:\t{}\nString2:\t{}\n".format(sampleString1, sampleString2))
  58. print("DP results:\nLCS:\t\t{}\nLCS length:\t{}\nTime:\t\t{}".format(dpLCS, len(dpLCS), dptime))
  59. print("\nRecursive results:\nLCS:\t\t{}\nLCS length:\t{}\nTime:\t\t{}".format(recLCS, len(recLCS), rectime))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement