Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. import re
  2. def find_paritions(lst, word, running=[]):
  3. for (index,item) in enumerate(lst):
  4. if index > 0:
  5. running.pop()
  6. running = running + [item]
  7. if item[1] == len(word):
  8. complete_paths.append(running)
  9. return
  10. to_explore = []
  11. end = item[1]
  12. for item_next in list_parition_index:
  13. if item_next[0] == end:
  14. to_explore.append(item_next)
  15. if len(to_explore) == 0:
  16. return
  17. find_paritions(to_explore,word,running)
  18.  
  19. return complete_paths
  20.  
  21. complete_paths=[]
  22. word = "ababbbabbababa"
  23. start = 0
  24. end = 1
  25. parition_count =0
  26. list_parition_index = []
  27. for start in range (len(word)):
  28. end=start+1
  29. while end < len(word) + 1:
  30. if word[start:end] == word[start:end][::-1]:
  31. list_parition_index.append([start,end])
  32. end +=1
  33. else:
  34. end +=1
  35. list_zeroes = [x for x in list_parition_index if x[0] == 0]
  36.  
  37.  
  38. x = find_paritions (list_zeroes,word)
  39. print(f"The total number of divisions required is {len(min(x,key=len))-1}")
  40. print(min(x,key=len))
  41.  
  42. #Uses dynamic programming
  43.  
  44. def find_partitions(s: str) -> int:
  45.  
  46. dp = [0]*len(s)
  47. for i in range(len(s)-2,-1,-1):
  48. dp[i] = 0 if s[i:]==s[i:][::-1] else 1 + min(dp[j] for j in range(i+1,len(s)) if s[i:j] == s[i:j][::-1])
  49. return dp[0]
  50.  
  51. def find_partitions_2(s: str) -> int:
  52.  
  53. cut = [x for x in range(-1, len(s))]
  54. for i in range(0,len(s)):
  55. for j in range(i, len(s)):
  56. if s[i:j] == s[j:i:-1]:
  57. cut[j+1] = min(cut[j+1], cut[i]+1)
  58. return cut[-1]
  59.  
  60. #%timeit find_partitions("ababbbabbababa")
  61. 80.7 µs ± 17.1 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  62.  
  63. #%timeit find_partitions_2("ababbbabbababa")
  64. 66.9 µs ± 9.84 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  65.  
  66. def find_partitions_3(s: str) -> int:
  67.  
  68. if not s: return -1
  69. if s == s[::-1]: return 0
  70. length = len(s)
  71. for i in range(1, length):
  72. if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
  73. return 1
  74. output = [-1] + [i for i in range(length)]
  75. is_palindrome = [[False] * (i + 1) for i in range(length)]
  76. for i in range(length):
  77. for j in range(i + 1):
  78. if s[i] == s[j] and (i - j < 2 or is_palindrome[i - 1][j + 1]):
  79. is_palindrome[i][j] = True
  80. output[i + 1] = min(output[i + 1], output[j] + 1)
  81. return output[length]
  82.  
  83. #%timeit find_partitions_3("ababbbabbababa")
  84. 48.9 µs ± 3.65 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement