|
| 1 | +def reverse_sequence_recursion(sequence): |
| 2 | + # e.g. |
| 3 | + # type('yes') <class 'str'> |
| 4 | + # type([9, 7, 1]) <class 'list'> |
| 5 | + # type((9, 7, 1)) <class 'tuple'> |
| 6 | + seq_type = type(sequence) |
| 7 | + |
| 8 | + # this type of operations are called 'reflection' |
| 9 | + # "a way of getting class names at runtime then crt objs of that class" |
| 10 | + empty_seq = seq_type() |
| 11 | + |
| 12 | + if sequence == empty_seq: |
| 13 | + return empty_seq |
| 14 | + |
| 15 | + # take [9, 7, 1] for example (a list of call frames) |
| 16 | + # [9, 7, 1] |
| 17 | + # [7, 1] |
| 18 | + # [1] |
| 19 | + # [] |
| 20 | + rest_reverse = reverse_sequence_recursion(sequence[1:]) |
| 21 | + |
| 22 | + # [] + [] PRODUCES [ ] |
| 23 | + # [ ] + [1] PRODUCES [1] |
| 24 | + # [ 1] + [7] PRODUCES [1, 7] |
| 25 | + # [ 1 7] + [9] PRODUCES [1, 7, 9] |
| 26 | + first = sequence[0:1] |
| 27 | + # the left side is the value being returned |
| 28 | + # the right side is the value of `first` |
| 29 | + |
| 30 | + return rest_reverse + first |
| 31 | + |
| 32 | + |
| 33 | +# references |
| 34 | +# concept |
| 35 | +# https://stackoverflow.com/a/37635/6273859 |
| 36 | +# concept with examples |
| 37 | +# see more |
| 38 | +# reflection in other languages |
| 39 | +# https://en.wikipedia.org/wiki/Reflective_programming |
| 40 | + |
| 41 | + |
| 42 | +def main(): |
| 43 | + assert reverse_sequence_recursion([9, 7, 1]) == [1, 7, 9] |
| 44 | + assert reverse_sequence_recursion((9, 7, 1)) == (1, 7, 9) |
| 45 | + assert reverse_sequence_recursion("rust") == "tsur" |
| 46 | + |
| 47 | + |
| 48 | +if "__main__" == __name__: |
| 49 | + main() |
0 commit comments