Skip to content

Commit 29a73bd

Browse files
committed
update urlify and add one test case
1 parent 7d0c549 commit 29a73bd

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

Python/chapter01/1.3 - URLify/miguel_1.3_sol.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,21 @@ def urlify(s: str, true_length: int) -> str:
2424
# Below link goes over string concat efficiency in python (I will use method 4
2525
# https://waymoot.org/home/python_string/
2626
# each space will make us replace it (with '%', then add 2 characters ('2', '0')
27-
result = ['\x00'] * len(s)*2 # extra buffer space
28-
i = 0
27+
# must count spaces first to help us find out the size of the
28+
result = ['\x00'] * true_length * 3
2929
space_count = 0
30-
added_chars_per_space = 2
31-
for c in s:
32-
if i == true_length + added_chars_per_space * space_count:
33-
break
34-
if c == ' ':
35-
result[i] = '%'
36-
result[i+1] = '2'
37-
result[i+2] = '0'
38-
i += 3
30+
chars_per_space = 2
31+
idx = 0
32+
for x in range(true_length):
33+
if s[idx - space_count * chars_per_space] == ' ':
34+
result[idx] = '%'
35+
result[idx + 1] = '2'
36+
result[idx + 2] = '0'
3937
space_count += 1
38+
idx += 3
4039
continue
41-
result[i] = c
42-
i += 1
40+
result[idx] = s[idx - space_count * chars_per_space]
41+
idx += 1
4342
return ''.join(result).rstrip('\x00')
4443

4544

@@ -73,7 +72,8 @@ def test_urlify(self):
7372
(("a b c d e f g h", 15), "a%20b%20c%20d%20e%20f%20g%20h"),
7473
(("a b c d e f g h ignore this", 15), "a%20b%20c%20d%20e%20f%20g%20h"),
7574
(("ihavenospaces", 13), "ihavenospaces"),
76-
(("nospacesIgnoreme", 8), "nospaces")
75+
(("nospacesIgnoreme", 8), "nospaces"),
76+
((" ", 1), "%20")
7777
]
7878
for args, expected in cases:
7979
self.assertEqual(urlify(*args), expected, msg=args)
@@ -86,7 +86,8 @@ def test_urlify_no_true_length(self):
8686
("a b c d e f g h", "a%20b%20c%20d%20e%20f%20g%20h"),
8787
("a b c d e f g h ignore this", "a%20b%20c%20d%20e%20f%20g%20h%20ignore%20this"),
8888
("ihavenospaces", "ihavenospaces"),
89-
("nospacesIgnoreme", "nospacesIgnoreme")
89+
("nospacesIgnoreme", "nospacesIgnoreme"),
90+
(" ", "%20")
9091
]
9192
for s, expected in cases:
9293
self.assertEqual(urlify_no_true_length(s), expected, msg=s)

0 commit comments

Comments
 (0)