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