473,890 Members | 1,791 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning True, False or None

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:

if True in lst:
return True
elif False in lst:
return False
else:
return None

This has a light code smell for me though -- can anyone see a simpler
way of writing this?

STeVe
Jul 18 '05
35 3411
Steven Bethard 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:

if True in lst:
return True
elif False in lst:
return False
else:
return None

This has a light code smell for me though -- can anyone see a simpler
way of writing this?


An attempt to short-circuit if possible:

def tristate(iterab le):
it = iter(iterable)
for item in it:
if item is not None:
return item or True in it

Not as elegant as max(), but makes me wonder whether a max() that accepts an
additional upper_bound argument and returns upper_bound as soon as it
encounters a value >= upper_bound would be worth the effort.

Peter

Jul 18 '05 #11
Fredrik Lundh wrote:
Steven Bethard wrote:
Raymond Hettinger wrote:

return max(lst)


Very clever! Thanks!


too clever. boolean > None isn't guaranteed by the language specification:


Yup. I thought about mentioning that for anyone who wasn't involved in
the previous thread discussing this behavior, but I was too lazy. ;)
Thanks for pointing it out again.

This implementation detail was added in Python 2.1a1, with the following
note[1]:

"The outcome of comparing non-numeric objects of different types is
not defined by the language, other than that it's arbitrary but
consistent (see the Reference Manual). An implementation detail changed
in 2.1a1 such that None now compares less than any other object. Code
relying on this new behavior (like code that relied on the previous
behavior) does so at its own risk."

Steve

[1] http://www.python.org/2.1/NEWS.txt
Jul 18 '05 #12
Jeremy Bowers wrote:
On Fri, 04 Feb 2005 10:48:44 -0700, Steven Bethard wrote:
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.


Yes, I see the smell, you are searching the list multiple times. You
could bail out when you can:

seenFalse = False
for item in list:
if item: return True
if item is False: seenFalse = True
if seenFalse:
return False
return None


I'd modify this approach slightly...

def tfn(lst):
answer = None
for item in lst:
if item is True: return True
if item is False: answer = False
return answer

But yeah, the original, straightforward way is probably enough clearer
that I wouldn't bother with anything else unless lists might be long
enough for performance to matter.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #13
"Steven Bethard"
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.


One more approach, just for grins:

s = set(lst)
return True in s or s == set([None]) and None
Raymond Hettinger
Jul 18 '05 #14
I'm seeing a consistent problem in most of these approaches.
Verbalized, the logic of the OP's original code reads as such:

If True is in the list *at all*, return True.
Otherwise, if False is in the list *at all*, return False.
Otherwise, return None.

So if we used Alex Martelli's code:
for val in lst:
if val is not None:
return val
return None


and the list was:

[ False , False , True , None ]

False would be returned upon inspection of the first index, even
though True was in fact in the list. The same is true of the code of
Jeremy Bowers, Steve Juranich, and Jeff Shannon. As for Raymond
Hettinger, I can't even be sure ;)

The original OP's code, on the other hand, inadvertently searches
through the list twice where once would have sufficed, causing a
needless performance pitfall. The following applies the OP's initial
logic while only iterating once:
def boolhunt( items ): falseExists = False
for item in items:
if item is True:
return True
elif item is False and not falseExists:
falseExists = True
if falseExists:
return False l1 = [ True , None , None , False ]
l2 = [ None , False , False , None ]
l3 = [ False , True , True , True ]
boolhunt( l1 ) True boolhunt( l2 ) False boolhunt( l3 )

True

It isn't elegant or clever, but it gets the job done :)

--
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
Jul 18 '05 #15
On Fri, 04 Feb 2005 16:44:48 -0500, Daniel Bickett wrote:
[ False , False , True , None ]

False would be returned upon inspection of the first index, even
though True was in fact in the list. The same is true of the code of
Jeremy Bowers, Steve Juranich, and Jeff Shannon. As for Raymond
Hettinger, I can't even be sure ;)


Nope. To recall, my code was:

seenFalse = False
for item in list:
if item: return True
if item is False: seenFalse = True
if seenFalse:
return False
return None

So, turning that into a real function and not a sketch:

Python 2.3.4 (#1, Jan 25 2005, 21:29:33)
[GCC 3.4.3 (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
def thingy(l): .... seenFalse = False
.... for item in l:
.... if item: return True
.... if item is False: seenFalse = True
.... if seenFalse:
.... return False
.... return None
.... thingy([ False , False , True , None ]) True


The defense rests, your honor. :-)

(I like the later use of "returnValu e" and the reduce solution was cute
and quite educational (very appropriate here). I deliberately eschewed
fanciness, though.)
Jul 18 '05 #16
Jeremy Bowers wrote:
The defense rests, your honor. :-)


I stand corrected :-) My apologies.

--
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
Jul 18 '05 #17
Fredrik Lundh wrote:
Steven Bethard wrote:
Raymond Hettinger wrote:

return max(lst)


Very clever! Thanks!


too clever. boolean > None isn't guaranteed by the language
specification:

http://docs.python.org/ref/comparisons.html

"... objects of different types always compare unequal, and are
ordered consistently but arbitrarily. /.../ In the future, the
comparison rules for objects of different types are likely to
change. ..."


Then maybe like this:
def max_of_two_with _None_less_than _any_other_obje ct(e1, e2): ... if e1 == None:
... return e2
... elif e2 == None:
... return e1
... else:
... return max(e1, e2)
reduce(max_of_t wo_with_None_le ss_than_any_oth er_object, lst)


Mick.
Jul 18 '05 #18
Jeremy Bowers wrote:
On Fri, 04 Feb 2005 16:44:48 -0500, Daniel Bickett wrote:
[ False , False , True , None ]

False would be returned upon inspection of the first index, even
though True was in fact in the list. The same is true of the code of
Jeremy Bowers, Steve Juranich, and Jeff Shannon. As for Raymond
Hettinger, I can't even be sure ;)


Nope.


Indeed. Similarly for mine, which was really just a slight transform
of Jeremy's (setting a return variable directly, instead of setting a
flag that's later used to decide what to return):
def tfn(lst): .... answer = None
.... for item in lst:
.... if item is True: return True
.... if item is False: answer = False
.... return answer
.... list = [False, False, True, None]
tfn(list) 1 list = [None, False, False, None]
tfn(list) 0 list = [None, None, None, None]
print tfn(list) None >>>


The noted logical flaw *has* been present in a number of proposed
solutions, however.

The key point to note is that one *must* examine the entire list
*unless* you find a True; short-circuiting on False means that you may
miss a later True.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #19
Daniel Bickett wrote:
def boolhunt( items ): ... falseExists = False
... for item in items:
... if item is True:
... return True
... elif item is False and not falseExists:
... falseExists = True
... if falseExists:
... return False


Or even shorter:
def boolhunt(items) : ... result = None
... for item in items:
... if item:
... return True
... elif result is None and item is False:
... result = False
... return result
Or like the Melmacians would do it:
def boolgen(items): ... result = None
... for item in items:
... if result:
... raise StopIteration
... elif item is not None:
... result = item
... yield result
[item for item in boolgen(a_list)][-1]

Mick.
Jul 18 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
7132
by: M-a-S | last post by:
Can anybody explain this: Python 2.3 (#46, Jul 29 2003, 18:54:32) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> None = 3 <stdin>:1: SyntaxWarning: assignment to None >>> False = 4 >>> True = 5 >>>
46
4278
by: Scott Chapman | last post by:
There seems to be an inconsistency here: Python 2.3.2 (#1, Oct 3 2003, 19:04:58) on linux2 >>> 1 == True True >>> 3 == True False >>> if 1: print "true" ....
2
1582
by: Rodney Maxwell | last post by:
In Python 2.4.1: >>> None = 99 SyntaxError: assignment to None >>> True = 99 >>> False = 99 >>> True == False True ----------------------- So why is 'None' special?
10
2448
by: randomtalk | last post by:
hello, i have another problem i feel that i have to be missing something.. Basically, i've written a recursive function to find all the prime up to a number (lim).. here is the function: The function basically takes in a list of all the prime number found, it takes the next number to be tested for (next) and the limit it will go up to. It divide next by the list of previous prime numbers if next is not bigger than lim, count up all the...
3
6955
by: Thirsty Traveler | last post by:
I have a gridview where the datasource is bound after a selection. The result of doing this is that sorting and paging do not work. I was given a sample of how to resolve this, however my attempt to explicity enable sorting failes because, unlike the sample, my sort event has a null in the datasource and I am unsure why this is so. Sample HTML code is: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"...
90
3509
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
13
2270
by: agent-s | last post by:
I have a function, generally described as so: def function(args): if condition: if condition2: function(args+1) elif condition3: print "text" return True else:
0
4110
by: cyberdawg999 | last post by:
Greetings all in ASP land I have overcome one obstacle that took me 2 weeks to overcome and I did it!!!!! I am so elated!! thank you to all who invested their time and energy towards helping me with my problems. Now for my new little problem,I had a problem posting the values from checkbox fields to a database and thats the obstacle I overcame. Now the second part is my new problem is that I want that the next time that page loads for...
12
18358
by: Karlo Lozovina | last post by:
I'm not sure if Python can do this, and I can't find it on the web. So, here it goes: try: some_function() except SomeException: some_function2() some_function3() ...
0
9976
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9815
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11215
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10802
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10451
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8008
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7160
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4665
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3267
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.