I am authoring the following question related to Numpy arrays.
"Write a function even_array(n) which returns a Numpy array containing even numbers 0 to 2n inclusive."
My specimen answer is
import numpy as np
def even_array(n):
return np.arange(0, n*2 + 2, 2)
which returns an array of floats. However, the student might choose to answer the question in a different way such as
import numpy as np
def even_array(n):
return np.array([2*i for i in range(n+1)])
This answer is also correct, but returns an array of integers.
A test case print(even_array(2)) with expected output [0. 2. 4] would pass the first answer but fail the second.
I could change the test case to the following:
print(even_array(2).astype(float))
but I think this could be confusing to the students, who won't have been introduced to different types of Numpy array at this point.
My proposed solution is to customise the template as follows, which also prevents the function returning something of type other than Numpy array (for example a Python list):
{{ STUDENT_ANSWER }}
__student_answer__ = """{{ STUDENT_ANSWER | e('py') }}"""
SEPARATOR = "#<ab@17943918#@>#"
import numpy as np
{% for TEST in TESTCASES %}
result = {{ TEST.testcode }}
if isinstance(result, np.ndarray):
print(result.astype(float))
else:
print("The function does not return a Numpy array.")
{% if not loop.last %}
print(SEPARATOR)
{% endif %}
{% endfor %}
I'd welcome any opinions on whether this is a sound solution, or whether there is a simpler or better way to make this work. I'm a novice Coderunner user so it is quite possible I've missed something obvious!