[Python] nearest coins from gold to copper (possibly bug)

Hello everyone. I’ve got pretty basic python code that should work but it doesn’t.

def filter_by_value(coins, value):
    return [item for item in coins if item.value == value]

    items = self.findItems()
    for val in [3, 2, 1]:
        filtered = filter_by_value(items, val)
        if filtered:
            nearest = self.findNearest(filtered)
            self.moveXY(nearest.pos.x, nearest.pos.y)

My intention is to collect nearest gold coin if it exists otherwise collect nearest silver coin if it exists otherwise - the same for copper.

Considering errors, it seems that branch if filtered: is executed even if filtered is an empty list.

Developers, any ideas what construction could drive the code parser crazy?

I’ve read lots of similar topics, but there were no solutions that would fit. Thank you.

Can you try if len(filtered): and see if your codes works as expected? If so, then probably there is a bug in CodeCombat’s Python parser/runtime that is not properly casting empty lists to false.

Thank you. len(filtered) did the trick. Should I post this as a bug on github?

Not exactly answering to your question, but rather a general suggestion for the problem: try to rate the coins based on their values and distance (value/distance), and pick up the one with the highest rating.


1 Like

I have had this problem many times, too. I always used an if filtered[0] to stop empty lists from running. Didn’t think about using len(filtered)

It should not be necessary, the bug is already reported here.

Both approaches are often used in languages where empty tuples/lists/arrays are considered “truthy” values, but these should not be necessary in Python (well, it currently is due to a bug in CodeCombat). Note that checking the value at index 0 will not work as expected if the first item in the list is a “falsy” value, that’s why I tend to prefer checking the list’s length. :wink:

1 Like