9
9
true_length and the other without.
10
10
"""
11
11
import unittest
12
- from typing import Callable
13
12
14
13
15
14
def urlify (s : str , true_length : int ) -> str :
@@ -24,13 +23,24 @@ def urlify(s: str, true_length: int) -> str:
24
23
"""
25
24
# Below link goes over string concat efficiency in python (I will use method 4
26
25
# 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
29
34
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
31
40
continue
32
- output .append (c )
33
- return '' .join (output )
41
+ result [i ] = c
42
+ i += 1
43
+ return '' .join (result ).rstrip ('\x00 ' )
34
44
35
45
36
46
def urlify_no_true_length (s : str ) -> str :
@@ -55,7 +65,7 @@ def urlify_no_true_length(s: str) -> str:
55
65
56
66
57
67
class TestUrlifyFunction (unittest .TestCase ):
58
- def _run_tests (self , f1 : Callable [[ str , int ], str ], f2 : Callable [[ str ], str ]) -> None :
68
+ def test_urlify (self ) :
59
69
cases = [
60
70
(("Mr John Smith " , 13 ), "Mr%20John%20Smith" ),
61
71
(("Miguel Hernandez" , 16 ), "Miguel%20Hernandez" ),
@@ -65,7 +75,11 @@ def _run_tests(self, f1: Callable[[str, int], str], f2: Callable[[str], str]) ->
65
75
(("ihavenospaces" , 13 ), "ihavenospaces" ),
66
76
(("nospacesIgnoreme" , 8 ), "nospaces" )
67
77
]
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 = [
69
83
("Mr John Smith" , "Mr%20John%20Smith" ),
70
84
("Miguel Hernandez" , "Miguel%20Hernandez" ),
71
85
(" Techqueria " , "%20Techqueria%20" ),
@@ -74,13 +88,8 @@ def _run_tests(self, f1: Callable[[str, int], str], f2: Callable[[str], str]) ->
74
88
("ihavenospaces" , "ihavenospaces" ),
75
89
("nospacesIgnoreme" , "nospacesIgnoreme" )
76
90
]
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 )
84
93
85
94
86
95
if __name__ == '__main__' :
0 commit comments