I'm trying to figure out the solution to this particular challenge and so far I'm stumped.
Basically, what I'm looking to do is:
Check if substring false exists in string s
If false exists in s, return the boolean True
However, I am not allowed to use any conditional statements at all.
Maybe there is a way to do this with objects?
There is always str.__contains__ if it's needed as a function somewhere:
In [69]: str.__contains__('**foo**', 'foo')
Out[69]: True
This could be used for things like filter or map:
sorted(some_list, key=partial(str.__contains__,'**foo**'))
The much more common usecase is to assign a truth value for each element in a list using a comprehension. Then we can make use of the in keyword in Python:
In[70]: ['foo' in x for x in ['**foo**','abc']]
Out[70]: [True, False]
The latter should always be preferred. There are edge cases where only a function might be possible.
But even then you could pass a lambda and use the statement:
sorted(some_list, key=lambda x: 'foo' in x)
Evaluating condition without using if statement:
True:
>>> s = 'abcdefalse'
>>> 'false' in s
True
False:
>>> s = 'abcdefals'
>>> 'false' in s
False
Return blank if False:
>>> s = 'abcdefals'
>>> 'false' in s or ''
''
Related
I am trying to create an if else code where there is about 20conditions for the elif, how do I create a list of conditions where i can just type something such as:
uno= <9
lol= >20
crad= =<3
list={uno,lol,crad}
if 13=list:
print("yay")
elif 13!=list:
print("nay")
That's my current code
It should print "yay", instead there is syntax error
It's not actually simpler than writing a chain of if/elif/elif etc, but something like this seems to do what you are asking:
predicates = [lambda x: x<9, lambda x: x>20, lambda x: x<=3]
if all(y(13) for y in predicates):
print("yay")
else:
print("nay")
Each predicate is a small anonymous function (a lambda) which receives a single argument and evaluates to either True or False. If you have a large number of arguments you want to check against a large set of predicates, it's nice to be able to encapsulate the predicates like this. The ability to programmatically add or remove predicates from the list truly extends the versatility of this construct beyond what you can (easily, naturally) do with if/elif/elif.
This particular set of predicates can't all be true for a single number. Maybe you want any() instead of all()...?
Your "conditions" are functions mapping the input to booleans. Therefore, you can write them as functions:
def is_small(number):
return number < 9
def is_large(number):
return number > 20
conditions = (is_small, is_large)
Then you can evaluate all of these functions on some input:
def check_all(input, conditions):
return [condition(input) for condition in conditions]
check_all(10, conditions)
>>> [False, False]
And if you want to know if all of these or any one of these are true, you can use the functions all and any:
any(check_all(10, conditions))
>>> False
any(check_all(21, conditions))
>>> True
And not all(…) is True if one of the conditions is not fulfilled, not any is True if none is.
Edit: One thing to notice is that the list comprehension [… for … in …] in check_all always evaluates all functions. This is not necessary if you use any or all, which can use an iterator and stop evaluating it onces the result it fixed (at the first True for any and the first False for all). If you use them, you can just replace the list comprehension [… for … in …] by a generator expression (… for … in …).
You could create a tuple of booleans and check it via all.
conditions = []
conditions.append(yourVar < 9)
conditions.append(yourVar > 20)
conditions.append(yourVar <= 3)
if all(conditions):
print('All conditions are met')
else:
print('At least one condition results in false)
Sometimes I want to check the logical value of an expression, so I type it in Python (or IPython) and get the result:
>>> a==3
True
But in other cases it doesn't work that way (here string is None):
>>> string
>>>
So I check the logical value like this:
>>> if string: print('True')
...
>>>
Is there a shorter way for checking the logical value of an expression?
Any function that returns True or False the same way it will be evaluated in an if-condition?
All expressions except those that produce None are echoed.
If you execute an expression that doesn't result in data being echoed, then you probably have a None result. You can test for None explicitly:
>>> string = None
>>> string is None
True
Using is None produces a non-None result.
If you just wanted to test for the boolean value of an expression, use the bool() function; it'll return a result following the standard truth value testing rules:
>>> string = None
>>> bool(string)
False
Again, this is guaranteed to not be None and echoed. You can't distinguish between None and other false-y values this way, however. An empty string '' will also result in False, for example.
Another alternative is to explicitly print all expression results, using the repr() function:
>>> print(repr(string))
None
This then produces the exact same output as echoing does, with the single exception that None is printed too.
Is there a shorter way for checking the logical value of an
expression?
Yes, it's the bool() function:
>>> string = None
>>> bool(string)
False
Yes, create a boolean directly from the expression, which will always be True or False:
>>> bool(string)
False
string is None or string is not None will return the boolean you need.
>>> string = None
>>> string is None
>>> True
This question already has answers here:
Is short-circuiting in assignment statements considered good style?
(2 answers)
Closed 7 years ago.
I was reading through an API's documentation when I came across a curious little set of statements:
self.use_ssl = kwargs.get('use_ssl', True)
self.scheme = self.use_ssl and 'https://' or 'http://'
After doing some personal testing, I found that if self.use_ssl was set to True, self.scheme would be set to use HTTPS, and HTTP if self.use_ssl was False. Awesomely pythonic, and I'll definitely be stealing this.
Can somebody explain exactly how this works?
In python, an empty string is equivalent to False, a non empty string is equivalent to True
>>> bool('')
False
>>> bool('foo')
True
The behavior of a boolean expression is described in the python 2 documentation, and is the same for python 3.
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
That's why you get the string 'https://' or 'http://' depending on the value of 'self.use_ssl'
Some examples, from the python console:
>>> True or ''
True
>>> True or 'foo'
True
>>> False or ''
''
>>> False or 'foo'
'foo'
>>> '' or True
True
>>> '' or False
False
>>> 'bar' or True
'bar'
>>> 'bar' or False
'bar'
>>> True and ''
''
>>> True and 'foo'
'foo'
>>> False and ''
False
>>> False and 'foo'
False
>>> '' and True
''
>>> '' and False
''
>>> 'bar' and True
True
>>> 'bar' and False
False
You can always convert a boolean expression to a real boolean value using bool()
>>> 1 and 'bar'
'bar'
>>> bool(1 and 'bar')
True
This trick, a and b or c, only works when b itself is a "truthy" value. Consider True and "" or "foo". You might expect it to produce the empty string, but it will produce foo, because True and "" results in the empty string, which is considered False when evaluating "" or "foo". The correct way would be to wrap b and c in a list to guarantee that the second argument to and is truthy (and that the overall result is a list in either case), then extract the first value of that list:
(a and [b] or [c])[0]
To avoid the clunkiness (and inefficiency) of creating and indexing a temporary list, Python introduced the conditional expression:
b if a else c
which does not rely on b having any particular boolean value.
it works like this:
when python interapt this it first checks the self.use_ssl if it is True
it continues in the AND chain to see if the next statement is True.
since the next statement is a string (and not an empty one) it is True
so there is no need to continue to the or since this statement is definetly True already, so the last value is used witch was 'https'
if use_ssl was false then there is no need to evaluate the and part of the condition since the first part is already false so python "skip" it and continue to the or part to check if that is True, since it is again a non empty string it is true, and again the last value used is "returned"
doing an exercise on CheckIO and I'm wondering as to why this won't work. Given a set of strings, I'm trying to return True if any of the strings are suffixes of any other string in the set. False otherwise. Using itertools I'm generating the necessary permutations in tuples first. Then for each tuple (each i), I wanted to see the hard way if the second tuple was in the end of the first tuple (option1). The otherway was using the .endwith function (option2), but neither will work for me. Why are these two options flawed?
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
#option1 ---- if i[1] in i[0][-len(i[1]):]:
#option2 ---- if i[0].endswith(i[1]):
return True
else:
return False
examples:
checkio({"hello", "lo", "he"}) == True
checkio({"hello", "la", "hellow", "cow"}) == False
I know this works as an answer. But just wondering why my original methods wouldn't take.
def checkio(words_set):
for w1 in words_set:
for w2 in words_set:
if w1.endswith(w2) and w1 != w2:
return True
return False
Your return False should be at the end of the for loop, otherwise the function will return True/False at every first comparison and will ignore all subsequent comparisons:
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
if i[0].endswith(i[1]):
return True
return False
Since it's an exercise, I won't give you the full answer, but are you sure that you really want to return False in the else clause?
Its because you return False right after the first check. and if it fails it will returns False you need to put it out of your for loop!
But as a more pythonic way you can use combinations and a generator expression within any function :
>>> from itertools import combinations
>>> s={"hello", "lo", "he"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s,2)))
True
>>> s2={"hello", "la", "hellow", "cow"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s2,2)))
False
I was testing a list to see if it's empty or not. Normally I use len(list) == 0 and I vaguely remembered reading a little while ago that the correct way to test if a list is empty was whether it was True or false.
So I tried list is False, and that returned False. Maybe I'm suppose to be using == ?
Nope, that also returned false. list is True, returned false as did list == True.
Now I'm confused so I do a quick google and end up at: Best way to check if a list is empty
The top answer is:
if not a:
print "List is empty"
So I search around some more and end up in the python manual where 4.1 states:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
any empty sequence, for example, '', (), [].
Now I'm plain confused. If I test a list as if not list, it works fine. But if an empty list is false, then why can't I just do if list is False or if list == False?
Thanks
An empty list is not False, but when you convert it to a boolean, it converts to False. Likewise for dicts, tuples, strings, etc.:
>>> [] == False
False
>>> bool([]) == False
True
>>> {} == False
False
>>> bool({}) == False
True
When you put something in the condition of an if clause, it is its boolean value that is used for testing the if. That's why if someList is the same as if bool(someList). Likewise, not foo does a boolean not, so not [] equals True.
As other have said, in python bool([]) == False. One thing that is frequently exploited by python programmers is that the operators and and or don't (necessarily) return True/False. Consider the following:
3 and 4 #returns 4
0 and 8 #returns 0 -- This is short-circuit evaluation
0 or 8 #returns 8
True or 0 #returns True -- This is short-circuit evaluation
[] or False #returns False
False or [] #returns []
What happens in an if statement is that the condition gets evaluated as above and then python implicitly calls bool on the result -- So you can think of it as:
if condition:
is the same thing as:
if bool(condition):
as far as python is concerned. Similarly for the not operator:
not condition
is the same thing as
not bool(condition)
mylist is False means "is the object named mylist exactly the same object as False?"
mylist == False means "is the object named mylist equal to False?
not mylist means "does the object named mylist behave falsily?
None of these are equivalent: 1 is not 1.0 but 1 == 1.0 and [] != False but not [] is True.
Comparing the list to False, and testing the list's truth or falsehood aren't quite the same thing. An empty list isn't equal to False, but behaves as False in a boolean context.
Here's another way to say it that might help this make sense:
print (bool([]) == False) # will print True
print ([] == False) # will print False