Skip to content

Commit 93044f9

Browse files
committed
urlify
1 parent 73fb371 commit 93044f9

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Python version 3.7.0
3+
1.3 - URLify
4+
Write a method to replace all spaces in a string with "%20". You may assume that the string has sufficient
5+
space at the end to hold the additional characters, and that you are given the "true" length of the string.
6+
(Note: If implementing in Java, please use a character array so that you can perform this operation in place)
7+
"""
8+
import unittest
9+
from typing import Callable
10+
11+
12+
def urlify(s: str, true_length: int) -> str:
13+
"""
14+
Given a string and it's "true" length, this function will return a new string
15+
that replaces all of the spaces of the input string with '%20'.
16+
Precondition(s):
17+
- length of s <= true_length
18+
:param s: the original string to 'urlify'
19+
:param true_length: since s may have additional characters, we focus on true_length instead of actual s length
20+
:return: string with each space from s replaced with '%20'
21+
"""
22+
output = ""
23+
for i, c in enumerate(s):
24+
if i == true_length:
25+
break
26+
if c == ' ':
27+
output += "%20"
28+
continue
29+
output += c
30+
return output
31+
32+
33+
class TestUrlifyFunction(unittest.TestCase):
34+
def _run_tests(self, f: Callable[[str, int], str]) -> None:
35+
cases = [
36+
("Mr John Smith ", 13, "Mr%20John%20Smith"),
37+
("Miguel Hernandez", 16, "Miguel%20Hernandez"),
38+
(" Techqueria ", 11, "%20Techqueria"),
39+
("a b c d e f g h", 15, "a%20b%20c%20d%20e%20f%20g%20h"),
40+
("a b c d e f g h ignore this", 15, "a%20b%20c%20d%20e%20f%20g%20h"),
41+
("ihavenospaces", 13, "ihavenospaces"),
42+
("nospacesIgnoreme", 8, "nospaces")
43+
]
44+
for case in cases:
45+
self.assertEqual(f(case[0], case[1]), case[2], msg=case)
46+
47+
def test_urlify(self):
48+
self._run_tests(urlify)
49+
50+
51+
if __name__ == '__main__':
52+
unittest.main()

0 commit comments

Comments
 (0)