Created
October 2, 2020 18:27
-
-
Save Ustice/a6ce66c7068e2b669d0462a0fe9cd4c8 to your computer and use it in GitHub Desktop.
A longest_sequence implementation in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def larger_of(a, b): | |
return a if a[1] > b[1] else b | |
def reset_to(index): | |
return [index, 1] | |
def is_sequential(a, b): | |
return a == b - 1 | |
def grow(vector): | |
return [vector[0], vector[1] + 1] | |
def longest_subsequence(array): | |
# [ index, length ] | |
largest = [0, 1] | |
current = [0, 1] | |
# Loop through the array, starting with the second element | |
for index in range(1, len(array)): | |
this = array[index] | |
previous = array[index - 1] | |
new_sequence = not(is_sequential(previous, this)) | |
largest = larger_of(current, largest) | |
current = reset_to(index) if new_sequence else grow(current) | |
# Check after last element | |
largest = larger_of(current, largest) | |
starting_index = largest[0] | |
ending_index = largest[0] + largest[1] | |
return array[starting_index : ending_index] | |
def test(name, value, expected): | |
if value == expected: | |
print('PASS: ' + name) | |
return | |
print('FAIL: ' + name + '\n Expected: ' + str(expected) + '\n Recieved: ' + str(value)) | |
case_empty = [] | |
case_one_element = [1] | |
case_largest_at_beginning = [1, 2, 3, 4, 5, 8] | |
case_largest_in_middle = [2, 1, 3, 6, 7, 8, 4, 5] | |
case_largest_at_end = [4, 5, 1, 0, 1, 2, 3] | |
case_with_negative = [7, -3, -2, -1, 0, 1, 16] | |
test('meta-test should fail', 'something else', 'something') | |
test('meta-test should pass', 'something', 'something') | |
print('--------------------------------') | |
test('empty array', longest_subsequence(case_empty), []) | |
test('single element', longest_subsequence(case_one_element), [1]) | |
test('largest at the beginning', longest_subsequence(case_largest_at_beginning), [1, 2, 3, 4, 5]) | |
test('largest in the middle', longest_subsequence(case_largest_in_middle), [6, 7, 8]) | |
test('largest at the end', longest_subsequence(case_largest_at_end), [0, 1, 2, 3]) | |
test('largest contains negative numbers', longest_subsequence(case_with_negative), [-3, -2, -1, 0, 1]) | |
# OUTPUT # | |
# FAIL: meta-test should fail | |
# Expected: something | |
# Recieved: something else | |
# PASS: meta-test should pass | |
# -------------------------------- | |
# PASS: empty array | |
# PASS: single element | |
# PASS: largest at the beginning | |
# PASS: largest in the middle | |
# PASS: largest at the end | |
# PASS: largest contains negative numbers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment