Advertisement
Guest User

Longest subsequence of two unique elements

a guest
Oct 11th, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.76 KB | None | 0 0
  1. def find_long_sseq(seq):
  2.     """Find the longest subsequence of seq which contains
  3.    no more than two distinct elements"""
  4.     if len(seq) < 3:
  5.         return seq
  6.     max_sub = seq[:2]
  7.     max_len = 2
  8.     curr_sub = seq[:2]
  9.     if seq[0]==seq[1]:
  10.         change_index = 0
  11.     else:
  12.         change_index = 1
  13.     for index, item in enumerate(seq):
  14.         if index < 2:
  15.             continue
  16.         if item in curr_sub:
  17.             curr_sub.append(item)
  18.             if item != seq[change_index]:
  19.                 change_index = index
  20.         else:
  21.             curr_sub = seq[change_index:index+1]
  22.             change_index = index
  23.         n = len(curr_sub)
  24.         if n > max_len:
  25.             max_sub = curr_sub
  26.             max_len = n
  27.     return max_sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement