Skip to content

Commit 9d18bbe

Browse files
author
shiv
committed
added string cutting code in python
1 parent 5e9a042 commit 9d18bbe

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

string_cutting.py

+34
Original file line numberDiff line numberDiff line change
@@ -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+
return tabular[s]
31+
32+
ans= solve('abaacaabaac')
33+
print(ans)
34+
print('solved in:', time.time()-start)

0 commit comments

Comments
 (0)