473,890 Members | 1,704 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 3412
Is it cheating to use a Set?

py>>def doit(thelist):
.... s = sets.Set(thelis t)
.... if s == sets.Set([None]):
.... return None
.... else:
.... return max(s)
....
py>>print doit([ True , None , None , False ] )
True
py>>print doit([ None , False , False , None ] )
False
py>>print doit([ False , True , True , True ] )
True
py>>print doit( [None, None, None, None] )
None

Jul 18 '05 #21
reduce(lambda x, y: x or y, lst)

works but when I tried

import operator
reduce(operator .or_, lst)

this did not work. It pukes

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool'

Any comments?

Fahri
Jul 18 '05 #22
sorry, that should have been:

py>>import sets
py>>def doit(thelist):
.... s = sets.Set(thelis t)
.... if s == sets.Set([None]):
.... return None
.... else:
.... return max(s - sets.Set([None]))

Jul 18 '05 #23
Fahri Basegmez wrote:
reduce(lambda x, y: x or y, lst)

works but when I tried

import operator
reduce(operator .or_, lst)

this did not work. It pukes

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool'

Any comments?

Fahri

TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool'

operator.or_ is "|" i.e., bitwise, not logical or

Michael

Jul 18 '05 #24

"Michael Spencer" <ma**@telcopart ners.com> wrote in message
news:ma******** *************** *************** *@python.org...
Fahri Basegmez wrote:
reduce(lambda x, y: x or y, lst)

works but when I tried

import operator
reduce(operator .or_, lst)

this did not work. It pukes

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool'

Any comments?

Fahri

TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool'

operator.or_ is "|" i.e., bitwise, not logical or

Michael


That explains it. Is there a logical or we can use with reduce?

Fahri
Jul 18 '05 #25
Fahri Basegmez wrote:
reduce(lambda x, y: x or y, lst)


This doesn't solve the OPs problem since
reduce(lambda x, y: x or y, [False, None])


returns None instead of False.

Mick.

Jul 18 '05 #26
Fahri Basegmez wrote:
"Michael Spencer" <ma**@telcopart ners.com> wrote in message
news:ma******** *************** *************** *@python.org...
Fahri Basegmez wrote:
reduce(lambd a x, y: x or y, lst)

works but when I tried

import operator
reduce(opera tor.or_, lst)

this did not work. It pukes

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool'

Any comments?

Fahri


TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool'

operator.or _ is "|" i.e., bitwise, not logical or

Michael

That explains it. Is there a logical or we can use with reduce?

Fahri

Yes, but it's not quite the same as the 'or' operator
bool.__or__(Tru e, False) True bool.__or__(Fal se, False) False bool.__or__(Fal se, None) NotImplemented


this may not be intentional...

Michael

Jul 18 '05 #27

"Mick Krippendorf" <ma******@gmx.d e> wrote in message
news:36******** *****@individua l.net...
Fahri Basegmez wrote:
reduce(lambda x, y: x or y, lst)


This doesn't solve the OPs problem since
reduce(lambda x, y: x or y, [False, None])


returns None instead of False.

Mick.


You are right.
I tested None or False and it worked. I assumed order did not matter for or
operator.

None or False returns False
False or None returns None

You know what they say about assumptions. Live and learn.

Fahri
Jul 18 '05 #28
Fahri Basegmez said unto the world upon 2005-02-04 23:14:
"Mick Krippendorf" <ma******@gmx.d e> wrote in message
news:36******** *****@individua l.net...
Fahri Basegmez wrote:
reduce(lambd a x, y: x or y, lst)


This doesn't solve the OPs problem since

>reduce(lam bda x, y: x or y, [False, None])


returns None instead of False.

Mick.

You are right.
I tested None or False and it worked. I assumed order did not matter for or
operator.

None or False returns False
False or None returns None

You know what they say about assumptions. Live and learn.

Fahri


Hi Fahri,

I don't have a reference at hand, but you might want to check the
docs' index or do a google for short circuit python or something similar.

or works by evaluating the first value and returning it if it
evaluates to True. Otherwise it returns the second.
0 or 42 42
Likewsie, and returns the first if it evaluates to False, otherwise it
returns the second. [] and 42 []


The idea is that the evaluation breaks out as soon as it has seen
enough to determine the result. Hence, short circuit. And, instead of
returning a Boolean, it returns the actual object flanking the
operator. Hence, the behaviour observed.

HTH,

Brian vdB

Jul 18 '05 #29
On Fri, 04 Feb 2005 13:04:16 -0500, rumours say that Steve Holden
<st***@holdenwe b.com> might have written:

[STeVe]
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.

[Stevbe]If you wanted to get clever you could write something like

for i in True, False:
if i in lst:
return i
return False


[!Steve]

You mistyped None as False in the last line. Your typos are getting worse every
day :)
--
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
Jul 18 '05 #30

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
18359
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
9977
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
9816
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
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...
1
10910
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9618
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8009
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
6036
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4667
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
3268
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.