Skip to content

Instantly share code, notes, and snippets.

@creativecomposer
Last active February 20, 2017 17:21
Show Gist options
  • Save creativecomposer/8167b0e47a008dc7a859ffb4ff87af71 to your computer and use it in GitHub Desktop.
Save creativecomposer/8167b0e47a008dc7a859ffb4ff87af71 to your computer and use it in GitHub Desktop.
Simple library function to find if a given sequence appears in the array somewhere.

Description

Simple library function in Python to find if a given sequence appears in the array somewhere.

How the code was developed

Initially the test function test_one_element_sequence() was added. Then enough code was written to make this test function pass. This TDD process was followed until sufficient test cases were written and code modified to make all tests pass.

##Usage The source code should be in the following directory structure:

  • Root folder
    • array_util
      • __init__.py (empty file)
      • array_util.py
    • tests
      • test_sequence_in_array.py

From the command line, cd to the tests folder and run

   python test_sequence_in_array.py

##Development environment The code was written on a Windows 7 machine with Python 3.5.1.

class ArrayUtil:
def is_sequence_present(self, input_array, sequence_to_check):
len_sequence = len(sequence_to_check)
if len_sequence == 0:
return False
for i in range((len(input_array) - len_sequence)+1):
if self.__get_no_of_sequence_elements_present(
input_array, i, sequence_to_check) == len(sequence_to_check):
return True
return False
def __get_no_of_sequence_elements_present(self, input_array,
index_to_start,
sequence_to_check):
len_sequence = len(sequence_to_check)
no_of_elements_present = 0
for array_idx, seq_idx in zip(range(index_to_start, index_to_start+len_sequence),
range(len_sequence)):
if input_array[array_idx] == sequence_to_check[seq_idx]:
no_of_elements_present = no_of_elements_present + 1
continue
else:
break
return no_of_elements_present
#!/usr/bin/env python3
import sys
import unittest
sys.path.append('..')
from array_util import array_util
class FindSequenceTest(unittest.TestCase):
def test_one_element_sequence(self):
self.assertTrue(array_util.ArrayUtil().is_sequence_present(
[3, 8, 1, 4], [1]))
def test_no_sequence_present(self):
self.assertFalse(array_util.ArrayUtil().is_sequence_present(
[3, 8, 1, 4], [1, 3, 4]))
def test_3_element_sequence(self):
self.assertTrue(array_util.ArrayUtil().is_sequence_present(
[3, 8, 99, 1, 3, 4, 6, 7], [1, 3, 4]))
def test_sequence_at_end(self):
self.assertTrue(array_util.ArrayUtil().is_sequence_present(
[3, 8, 99, 1, 3, 4, 6, 7], [6, 7]))
def test_empty_sequence(self):
self.assertFalse(array_util.ArrayUtil().is_sequence_present(
[1, 2, 3], []))
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment