Skip to content

Commit c709cc6

Browse files
one away solution python3
1 parent ee1d3fc commit c709cc6

File tree

1 file changed

+42
-0
lines changed
  • Python/chapter01/1.5 - OneAway

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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()

0 commit comments

Comments
 (0)