File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change
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!"
You can’t perform that action at this time.
0 commit comments