Skip to content

Commit 7d0c549

Browse files
committed
change test code, try out non-pythonic way
1 parent bff1cf7 commit 7d0c549

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

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

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
true_length and the other without.
1010
"""
1111
import unittest
12-
from typing import Callable
1312

1413

1514
def urlify(s: str, true_length: int) -> str:
@@ -24,13 +23,24 @@ def urlify(s: str, true_length: int) -> str:
2423
"""
2524
# Below link goes over string concat efficiency in python (I will use method 4
2625
# https://waymoot.org/home/python_string/
27-
output = []
28-
for c in s[0:true_length]:
26+
# 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
29+
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
2934
if c == ' ':
30-
output.append("%20")
35+
result[i] = '%'
36+
result[i+1] = '2'
37+
result[i+2] = '0'
38+
i += 3
39+
space_count += 1
3140
continue
32-
output.append(c)
33-
return ''.join(output)
41+
result[i] = c
42+
i += 1
43+
return ''.join(result).rstrip('\x00')
3444

3545

3646
def urlify_no_true_length(s: str) -> str:
@@ -55,7 +65,7 @@ def urlify_no_true_length(s: str) -> str:
5565

5666

5767
class TestUrlifyFunction(unittest.TestCase):
58-
def _run_tests(self, f1: Callable[[str, int], str], f2: Callable[[str], str]) -> None:
68+
def test_urlify(self):
5969
cases = [
6070
(("Mr John Smith ", 13), "Mr%20John%20Smith"),
6171
(("Miguel Hernandez", 16), "Miguel%20Hernandez"),
@@ -65,7 +75,11 @@ def _run_tests(self, f1: Callable[[str, int], str], f2: Callable[[str], str]) ->
6575
(("ihavenospaces", 13), "ihavenospaces"),
6676
(("nospacesIgnoreme", 8), "nospaces")
6777
]
68-
cases_no_true_length = [
78+
for args, expected in cases:
79+
self.assertEqual(urlify(*args), expected, msg=args)
80+
81+
def test_urlify_no_true_length(self):
82+
cases = [
6983
("Mr John Smith", "Mr%20John%20Smith"),
7084
("Miguel Hernandez", "Miguel%20Hernandez"),
7185
(" Techqueria ", "%20Techqueria%20"),
@@ -74,13 +88,8 @@ def _run_tests(self, f1: Callable[[str, int], str], f2: Callable[[str], str]) ->
7488
("ihavenospaces", "ihavenospaces"),
7589
("nospacesIgnoreme", "nospacesIgnoreme")
7690
]
77-
for args, expected in cases:
78-
self.assertEqual(f1(*args), expected, msg=args)
79-
for s, expected in cases_no_true_length:
80-
self.assertEqual(f2(s), expected, msg=s)
81-
82-
def test_urlify(self):
83-
self._run_tests(urlify, urlify_no_true_length)
91+
for s, expected in cases:
92+
self.assertEqual(urlify_no_true_length(s), expected, msg=s)
8493

8594

8695
if __name__ == '__main__':

0 commit comments

Comments
 (0)