forked from learning-zone/python-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecursive_index.py
102 lines (61 loc) · 2.08 KB
/
recursive_index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
def recursive_index(needle, haystack):
"""Given list (haystack), return index (0-based) of needle in the list.
Return None if needle is not in haystack.
Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP.
>>> lst = ["hey", "there", "you"]
>>> recursive_index("hey", lst)
0
>>> recursive_index("you", lst)
2
>>> recursive_index("porcupine", lst) is None
True
"""
if not haystack or needle not in haystack:
return None
count = 0
if needle == haystack[0]:
return count
count += 1 + recursive_index(needle, haystack[1:])
return count
def recursive_index_2(needle, haystack):
"""Given list (haystack), return index (0-based) of needle in the list.
Return None if needle is not in haystack.
Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP.
>>> lst = ["hey", "there", "you"]
>>> recursive_index_2("hey", lst)
0
>>> recursive_index_2("you", lst)
2
>>> recursive_index_2("porcupine", lst) is None
True
"""
if not haystack or needle not in haystack:
return None
if needle == haystack[0]:
return 0
else:
return 1 + recursive_index_2(needle, haystack[1:])
def recursive_index_3(needle, haystack):
"""Given list (haystack), return index (0-based) of needle in the list.
Return None if needle is not in haystack.
Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP.
>>> lst = ["hey", "there", "you"]
>>> recursive_index_3("hey", lst)
0
>>> recursive_index_3("you", lst)
2
>>> recursive_index_3("porcupine", lst) is None
True
"""
def _recursive_index_3(needle, haystack, count):
if len(haystack) == count:
return None
if needle == haystack[count]:
return count
return _recursive_index_3(needle, haystack, count+1)
return _recursive_index_3(needle, haystack, 0)
if __name__ == '__main__':
import doctest
results = doctest.testmod()
if results.failed == 0:
print "ALL TESTS PASSED!"