File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Python/chapter01/1.5 - OneAway Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/python3
2
+ import unittest
3
+
4
+
5
+ def one_away (s1 , s2 ):
6
+ '''Given two strings, write a function to check if
7
+ they are one edit (or zero edits) away.'''
8
+ if abs (len (s1 ) - len (s2 )) > 1 :
9
+ return False
10
+
11
+ str1 = s1 if len (s1 ) < len (s2 ) else s2
12
+ str2 = s2 if len (s1 ) < len (s2 ) else s1
13
+ idx1 , idx2 = 0 , 0
14
+ diff = False
15
+
16
+ while idx1 < len (str1 ) and idx2 < len (str2 ):
17
+ if str1 [idx1 ] is not str2 [idx2 ]:
18
+ if diff :
19
+ return False
20
+ diff = True
21
+
22
+ if len (str1 ) is len (str2 ):
23
+ idx1 += 1
24
+ else :
25
+ idx1 += 1
26
+ idx2 += 1
27
+
28
+ return True
29
+
30
+
31
+ class Test (unittest .TestCase ):
32
+ def test1 (self ):
33
+ s1 = "Tact Cat"
34
+ s2 = "TactCat"
35
+ s3 = "nick"
36
+ s4 = "jeff"
37
+ self .assertTrue (one_away (s1 , s2 ))
38
+ self .assertFalse (one_away (s3 , s4 ))
39
+
40
+
41
+ if __name__ == '__main__' :
42
+ unittest .main ()
You can’t perform that action at this time.
0 commit comments