I recently applied for a job as a Python coder but was rejected.
This was the problem:
Write a python code to check if an array has a sequence (1,3,4)
Assuming they were looking for expert Python programmers, what could I have done better?
# Tested with Python 2.7
import unittest
# Runtime: O(n)
def doesSeqAppear(int_arr):
#check if input is a list
if not isinstance(int_arr, list):
raise TypeError("Input shall be of type array.")
# check all elements are of type int
if not all(isinstance(item, int) for item in int_arr) :
raise ValueError("All elements in array shall be of type int.")
arr_len = len(int_arr)
if arr_len < 3:
return False
# Loop through elements
for i in range(arr_len-2):
if int_arr[i] == 1 and \
int_arr[i+1] == 3 and \
int_arr[i+2] == 4 :
return True
return False
class TestMethodDoesSeqAppear(unittest.TestCase):
def test_only_single_seq(self):
#Single time
assert doesSeqAppear([1,3,4]) == True
def test_multiple_seq(self):
#multiple
assert doesSeqAppear([2,2,1,3,4,2,1,3,4]) == True
def test_neg_seq(self):
#multiple
assert doesSeqAppear([9,-1,1,3,4,-4,4]) == True
def test_only_empty_seq(self):
#empty
assert doesSeqAppear([]) == False
def test_only_single_elem_seq(self):
#Single element
assert doesSeqAppear([1]) == False
def test_input_is_none(self):
self.assertRaises(TypeError, doesSeqAppear, None)
def test_raises_type_error(self):
self.assertRaises(TypeError, doesSeqAppear, "string")
def test_raises_value_error(self):
self.assertRaises(ValueError, doesSeqAppear, [1,2,'a', 'b'])
if __name__ == '__main__':
unittest.main()
#
['a','b','c',1,3,4]
seems like a valid sequence that would return false in your implementation – Navidad20 Dec 14 '16 at 14:36xrange
? ;) – Tamoghna Chowdhury Dec 14 '16 at 14:38numpy.array
instead of a list? With NumPy arrays, this could be done in 2 function calls. – Tamoghna Chowdhury Dec 14 '16 at 14:43str([1,3,4])[1:-1] in str([array])
? – Samuel Shifterovich Dec 14 '16 at 21:41