File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed
Python/chapter01/1.5 - OneAway Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ One Away: There are three types of edits that can be performed on strings:
3
+ insert a character, remove a character, or replace a character. Given two
4
+ strings, write a function to check if they are one edit (or zero edits) away.
5
+ EXAMPLE
6
+ pale, ple -> true
7
+ pales, pale -> true
8
+ pale, bale -> true
9
+ pale, bake -> false
10
+ Hints:#23, #97, #130
11
+ """
12
+
13
+ def oneAway (str1 ,str2 ):
14
+ str1 = str1 .lower ()
15
+ str2 = str2 .lower ()
16
+ d = {}
17
+ for i in str1 :
18
+ if i in d :
19
+ d [i ] = + 1
20
+ else :
21
+ d [i ] = 1
22
+
23
+ for j in str2 :
24
+ if j in d :
25
+ d [j ] -= 1
26
+
27
+ else :
28
+ d [j ] = 1
29
+ count = 0 # count the number of times
30
+
31
+
32
+ """
33
+ My thought on how to do this:
34
+ So knowing the pale and ple
35
+ when we subtract it from the hash table we know there should be a value of 1
36
+ for removal of one letter
37
+
38
+ The insertation of one letter should only leave the key of one
39
+ pales and pale
40
+
41
+ The interseting stuff happens when you have a change of letter.
42
+ The letter gets counting when you place it in the hash table
43
+ pale bale.
44
+ We use count to count the number of time count can be one. You'll find
45
+ that replaceing a letter is going to make count two v's of one
46
+
47
+ replacing two letter will make v's count more onces
48
+
49
+ You'll see this when you print k and v
50
+
51
+ """
52
+ for k ,v in d .items ():
53
+ #print(k,v)
54
+ if v == 1 :
55
+ count += 1
56
+
57
+ if count <= 2 : #
58
+ return True
59
+
60
+ else :
61
+ return False
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+ print (oneAway ('pale' , 'ple' ))#True
72
+ print (oneAway ('pales' , 'pale' ))#True
73
+ print (oneAway ('pale' , 'bale' ))#True
74
+
75
+ print (oneAway ('pale' , 'bake' ))#False
You can’t perform that action at this time.
0 commit comments