by blahedo · 12y ago · 0 comments
boolean lookForSomething(int parameter) {
for (Item item: list) {
if (item.matches(parameter))
return true;
else
return false;
}
}
where a correct answer would omit the "else" and put the "return false;" outside the bracketed loop (or, keep a boolean variable updated and then return that after the loop is done. Let's translate that to python: def lookForSomething(parameter):
for item in list:
if matches(item, parameter):
return true
else:
return false
As a conceptual matter, for a beginner who is still trying to nail down the whole notion of "can stop early when found, but have to scan the whole list if not found", it is just plain nasty that the following code is not only correct but idiomatic: def lookForSomething(parameter):
for item in list:
if matches(item, parameter):
return true
else:
return falseThe `else` there is superfluous; that cuts it down to this:
def look_for_something(parameter):
for item in list:
if matches(item, parameter):
return True
return False
And then after that one should just replace the entire loop with an `any` call: def look_for_something(parameter):
return any(matches(item, parameter) for item in list)
Also, if we assume a `matches()` that is simple equality, then it would just be def look_for_something(parameter):
return parameter in list
… and even then, you shouldn’t have named a variable `list`.Cut down to its essence like this, the function probably shouldn’t have even existed… ☺