We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 5e9a042 commit 9d18bbeCopy full SHA for 9d18bbe
string_cutting.py
@@ -0,0 +1,34 @@
1
+#-*-coding:utf8;-*-
2
+#qpy:3
3
+#qpy:console
4
+
5
+costs = {'a':1,
6
+ 'b':1,
7
+ 'c':1,
8
+ 'aba':2,
9
+ 'caa':2,
10
+ 'baac':3}
11
+import time
12
+start = time.time()
13
14
+# minimum string cost
15
+# very similar to rod cutting
16
17
+tabular = {}
18
+def solve(s):
19
+ if s in tabular: return tabular[s]
20
+ if len(s) == 1 and s in costs:
21
+ tabular[s] = costs[s]
22
+ return tabular[s]
23
+ if len(s) < 1: return 0
24
+ c=[]
25
+ for i in range(len(s)):
26
+ if s[-i:] in costs:
27
+ c.append(solve(s[:-i])+costs[s[-i:]])
28
+ print(s, min(c), c)
29
+ tabular[s] = min(c)
30
31
32
+ans= solve('abaacaabaac')
33
+print(ans)
34
+print('solved in:', time.time()-start)
0 commit comments