returning True, False or None
Brian van den Broek
bvande at po-box.mcgill.ca
Fri Feb 4 13:31:15 EST 2005
Alex Martelli said unto the world upon 2005-02-04 13:02:
> Steven Bethard <steven.bethard at gmail.com> wrote:
>
>
>>I have lists containing values that are all either True, False or None,
>>e.g.:
>>
>> [True, None, None, False]
>> [None, False, False, None ]
>> [False, True, True, True ]
>> etc.
>>
>>For a given list:
>>* If all values are None, the function should return None.
>>* If at least one value is True, the function should return True.
>>* Otherwise, the function should return False.
>>
>>Right now, my code looks like:
<SNIP OP's code>
>>This has a light code smell for me though -- can anyone see a simpler
>>way of writing this?
>
>
> What about...:
>
> for val in lst:
> if val is not None:
> return val
> return None
>
> or the somewhat fancy/clever:
>
> for val in (x for x in lst if x is not None):
> return val
> return None
>
>
> Alex
These don't do what the OP desired.
.>>> test_case = [False, True, True, True ]
.>>> def alexs_funct(lst):
. for val in lst:
. if val is not None:
. return val
. return None
>>> alexs_funct(test_case)
False
But, by the 'spec', it ought return True.
Best,
Brian vdB
A mere newbie, quite pleased with himself for finding a problem with
'bot code -- next scheduled to occur mid 2011 :-)
More information about the Python-list
mailing list