As part of an online programming course (6.00.1x), I'm asked (Quiz p8) to create a function, satisfiesF(L)
, that filters L
in-place using f
, then returns the length of L
.
f
is a function defined for me that returnsTrue
for items that should remain in the list- The remaining list items should be in the same order as before
I've written 2 solutions to this problem, tested them, and submitted them, but both were rejected. No reason was provided, as the problem is designed to test our ability to come up with our own test cases. For this reason, please do not provide working code, but rather give me a general idea of what's going wrong. I see 3 main possibilities at the moment:
- I have misunderstood the problem
- I made a subtle programming mistake
- edX made a mistake with their test cases (unlikely)
Here are my 2 solutions:
def satisfiesL(L):
L[:] = [i for i in L if f(i)]
return len(L)
def satisfiesL(L):
i = 0
while len(L) > i:
if f(L[i]): i += 1
else: L.pop(i)
Here is the full description of the problem verbatim:
Write a Python function called
satisfiesF
that has the specification below. Then make the function callrun_satisfiesF(L, satisfiesF)
. Your code should look like:def satisfiesF(L): """ Assumes L is a list of strings Assume function f is already defined for you and it maps a string to a Boolean Mutates L such that it contains all of the strings, s, originally in L such that f(s) returns True, and no other elements. Remaining elements in L should be in the same order. Returns the length of L after mutation """ # Your function implementation here run_satisfiesF(L, satisfiesF)
For your own testing of
satisfiesF
, for example, see the following test functionf
and test code:def f(s): return 'a' in s L = ['a', 'b', 'a'] print satisfiesF(L) print L
Should print:
2 ['a', 'a']
Paste your entire function
satisfiesF
, including the definition, in the box below. After you define your function, make a function call torun_satisfiesF(L, satisfiesF)
. Do not definef
orrun_satisfiesF
. Do not leave any debugging print statements.For this question, you will not be able to see the test cases we run. This problem will test your ability to come up with your own test cases.
And, for the sake of completeness, here are my latest set of tests (I'm using [doctest
]):
>>> L = ['bat', 'cat', 'dog', 'elephant']
>>> satisfiesF(L) == len([i for i in L if f(i)])
True
>>> [i for i in L if not f(i)]
[]
>>> L = ['ab', 'b', 'ac']
>>> satisfiesF(L)
2
>>> L
['ab', 'ac']
>>> L = ['a', 'a', 'b']
>>> satisfiesF(L)
2
>>> L
['a', 'a']
>>> L = ['a', 'a', 'a']
>>> satisfiesF(L)
3
>>> L
['a', 'a', 'a']
>>> L = ['b', 'c', 'd', 'a']
>>> satisfiesF(L)
1
>>> L
['a']
I've tried replacing satisfiesF(L)
with run_satisfiesF(L, satisfiesF)
, but the tests still pass.
Other questions about 6.00.1x Quiz p8
Aucun commentaire:
Enregistrer un commentaire