Lecture "Brute-force algorithms", exercise 3
essepuntato opened this issue ยท 6 comments
Write in Python the function def my_enumerate(input_list)
which behaves like the built-in function enumerate()
introduced in Section "Linear search" and returns a proper list, and accompany the function with the related test case. It is not possible to use the built-in function enumerate()
in the implementation.
def my_enumerate(input_list):
output_enumerate_object = []
for index in range(len(input_list)):
tuple = (index, input_list[index])
output_enumerate_object.append(tuple)
return output_enumerate_object
def test_my_enumerate(input_list, expected):
result = my_enumerate(input_list)
if result == expected:
return True
else:
return False
print(test_my_enumerate(["Remember", "the", "fifth", "of", "November"], [(0, 'Remember'), (1, 'the'), (2, 'fifth'), (3, 'of'), (4, 'November')]))
# It prints True
def my_enumerate(input_list):
input_length = len(input_list)
output = [(index, input_list[index]) for index in range(input_length)]
return output
def test_my_enumerate(input, expected)
return my_enumerate(input) == expected
volumes = ['Preludes and Nocturnes', 'The Dolls House', 'Dream Country', 'Season of Mists', 'A Game of You', 'Fables and Reflections', 'Brief Lives', 'Worlds End', 'The Kindly Ones', 'The Wake']
print(test_my_enumerate(volumes, [(0, 'Preludes and Nocturnes'), (1, 'The Dolls House'), (2, 'Dream Country'), (3, 'Season of Mists'), (4, 'A Game of You'), (5, 'Fables and Reflections'), (6, 'Brief Lives'), (7, 'Worlds End'), (8, 'The Kindly Ones'), (9, 'The Wake')]))
Hi all,
please find attached my personal solution โ also available online:
# Test case for the function
def test_my_enumerate(input_list, expected):
result = my_enumerate(input_list)
if expected == result:
return True
else:
return False
# Code of the function
def my_enumerate(input_list):
l = list()
for i in range(len(input_list)):
l.append((i, input_list[i]))
return l
# Tests
print(test_my_enumerate([], []))
print(test_my_enumerate(["a", "b", "c"], [(0, "a"), (1, "b"), (2, "c")]))
An important point: the rationale of using TDD to test the code is that all the tests must be passed (and this, somehow, guarantees the correctness of the code). If a test is not passed, it means that there is something wrong in the code. Thus, please, avoid using tests that fail on purpose since this does not demonstrate the correctness of your code.
def my_enumerate(input_list):
#implement the enumerate action without using enumerate()
output_list = []
for i in range(len(input_list)):
output_list.append((i, input_list[i]))
return output_list
print(my_enumerate([1, 2, 3, 4])==list(enumerate([1, 2, 3, 4])))
#It prints True