Skip to content

Commit efe973c

Browse files
committed
Create reverse_string.py
1 parent 6449b36 commit efe973c

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

reverse_string.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Given a string, return the same string, reversed.
2+
# can't use .reverse()
3+
4+
def rev_str(string):
5+
"""
6+
>>> rev_str('hello')
7+
'olleh'
8+
9+
>>> rev_str('1234h')
10+
'h4321'
11+
12+
>>> rev_str('')
13+
''
14+
"""
15+
16+
# Runtime: O(n)
17+
18+
reversed_str = ""
19+
list_str = list(string)
20+
# ['h', 'e', l, l, o]
21+
for l in range(len(list_str)):
22+
letter = list_str.pop()
23+
# l
24+
reversed_str += letter
25+
# oll
26+
return reversed_str
27+
28+
29+
def rev_str_2(string):
30+
"""
31+
>>> rev_str_2('hello')
32+
'olleh'
33+
34+
>>> rev_str_2('1234h')
35+
'h4321'
36+
37+
>>> rev_str_2('')
38+
''
39+
"""
40+
41+
# Runtime: O(n)
42+
43+
return string[::-1]
44+
45+
46+
def rev_str_3(string):
47+
"""
48+
>>> rev_str_3('hello')
49+
'olleh'
50+
51+
>>> rev_str_3('1234h')
52+
'h4321'
53+
54+
>>> rev_str_3('')
55+
''
56+
"""
57+
58+
# Runtime: O(n)
59+
60+
if len(string) == 0:
61+
return string
62+
63+
return string[-1] + rev_str_3(string[:-1])
64+
65+
66+
67+
if __name__ == '__main__':
68+
import doctest
69+
results = doctest.testmod()
70+
71+
if results.failed == 0:
72+
print "ALL TESTS PASSED!"

0 commit comments

Comments
 (0)