Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 36 additions & 26 deletions dynamic_programming/longest_increasing_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,52 @@
This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence.

The problem is :
Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
Given an array, to find the longest and increasing sub ARRAY in that given array and return it.
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
"""


def longestSub(ARRAY): # This function is recursive

ARRAY_LENGTH = len(ARRAY)
from typing import List


def longest_subsequence(Array: List[int]) -> List[int]: # This function is recursive
"""
Some examples
>>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80])
[10, 22, 33, 41, 60, 80]
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])
[1, 2, 3, 9]
>>> longest_subsequence([9, 8, 7, 6, 5, 7])
[8]
>>> longest_subsequence([1, 1, 1])
[1, 1, 1]
"""
ArrayLength = len(Array)
if (
ARRAY_LENGTH <= 1
ArrayLength <= 1
): # If the array contains only one element, we return it (it's the stop condition of recursion)
return ARRAY
return Array
# Else
PIVOT = ARRAY[0]
Pivot = Array[0]
isFound = False
i = 1
LONGEST_SUB = []
while not isFound and i < ARRAY_LENGTH:
if ARRAY[i] < PIVOT:
LongestSubseq = []
while not isFound and i < ArrayLength:
if Array[i] < Pivot:
isFound = True
TEMPORARY_ARRAY = [element for element in ARRAY[i:] if element >= ARRAY[i]]
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY)
if len(TEMPORARY_ARRAY) > len(LONGEST_SUB):
LONGEST_SUB = TEMPORARY_ARRAY
TempArray = [element for element in Array[i:] if element >= Array[i]]
TempArray = longest_subsequence(TempArray)
if len(TempArray) > len(LongestSubseq):
LongestSubseq = TempArray
else:
i += 1

TEMPORARY_ARRAY = [element for element in ARRAY[1:] if element >= PIVOT]
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY)
if len(TEMPORARY_ARRAY) > len(LONGEST_SUB):
return TEMPORARY_ARRAY
TempArray = [element for element in Array[1:] if element >= Pivot]
TempArray = [Pivot] + longest_subsequence(TempArray)
if len(TempArray) > len(LongestSubseq):
return TempArray
else:
return LONGEST_SUB


# Some examples
return LongestSubseq


print(longestSub([4, 8, 7, 5, 1, 12, 2, 3, 9]))
print(longestSub([9, 8, 7, 6, 5, 7]))
if __name__ == "__main__":
import doctest
doctest.testmod()