write a function that takes as an argument a list and a string, and returns a boolean based on whether or not all the letters in the string appear somewhere in the list.
my_function(["hello","world"],"hold")
should return True
and
my_function(["hello","world"],"down")
should return False
This function will take in the input arr and string and compute, as you would expect. To explain the code, I start by building an 'index' to compare against, I called it, di. From there I loop through every character of every string inside of arr. From there, if they are all true, then return true, otherwise false. As for how that comparison was written (all(di[key] for key in di) it builds a true and false tuple and then all checks if all items in the list-like item are true.
def my_function(arr,string):
di = {c:False for c in string}
for value in arr:
for character in value:
if character in di:
di[character] = True
return all(di[key] for key in di)
Related
I just learned there are truthy and falsy values in python which are different from the normal True and False.
Can someone please explain in depth what truthy and falsy values are? Where should I use them? What is the difference between truthy and True values and falsy and False values?
We use "truthy" and "falsy" to differentiate from the bool values True and False. A "truthy" value will satisfy the check performed by if or while statements. As explained in the documentation, all values are considered "truthy" except for the following, which are "falsy":
None
False
Numbers that are numerically equal to zero, including:
0
0.0
0j
decimal.Decimal(0)
fraction.Fraction(0, 1)
Empty sequences and collections, including:
[] - an empty list
{} - an empty dict
() - an empty tuple
set() - an empty set
'' - an empty str
b'' - an empty bytes
bytearray(b'') - an empty bytearray
memoryview(b'') - an empty memoryview
an empty range, like range(0)
objects for which
obj.__bool__() returns False
obj.__len__() returns 0, given that obj.__bool__ is undefined
As the comments described, it just refers to values which are evaluated to True or False.
For instance, to see if a list is not empty, instead of checking like this:
if len(my_list) != 0:
print("Not empty!")
You can simply do this:
if my_list:
print("Not empty!")
This is because some values, such as empty lists, are considered False when evaluated for a boolean value. Non-empty lists are True.
Similarly for the integer 0, the empty string "", and so on, for False, and non-zero integers, non-empty strings, and so on, for True.
The idea of terms like "truthy" and "falsy" simply refer to those values which are considered True in cases like those described above, and those which are considered False.
For example, an empty list ([]) is considered "falsy", and a non-empty list (for example, [1]) is considered "truthy".
See also this section of the documentation.
Python determines the truthiness by applying bool() to the type, which returns True or False which is used in an expression like if or while.
Here is an example for a custom class Vector2dand it's instance returning False when the magnitude (lenght of a vector) is 0, otherwise True.
import math
class Vector2d(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
a = Vector2d(0,0)
print(bool(a)) #False
b = Vector2d(10,0)
print(bool(b)) #True
Note: If we wouldn't have defined __bool__ it would always return True, as instances of a user-defined class are considered truthy by default.
Example from the book: "Fluent in Python, clear, concise and effective programming"
Truthy values refer to the objects used in a boolean context and not so much the boolean value that returns true or false.Take these as an example:
>>> bool([])
False
>>> bool([1])
True
>>> bool('')
False
>>> bool('hello')
True
Where should you use Truthy or Falsy values ?
These are syntactic sugar, so you can always avoid them, but using them can make your code more readable and make you more efficient.
Moreover, you will find them in many code examples, whether in python or not, because it is considered good practice.
As mentioned in the other answers, you can use them in if tests and while loops. Here are two other examples in python 3 with default values combined with or, s being a string variable. You will extend to similar situations as well.
Without truthy
if len(s) > 0:
print(s)
else:
print('Default value')
with truthy it is more concise:
print(s or 'Default value')
In python 3.8, we can take advantage of the assignment expression :=
without truthy
if len(s) == 0:
s = 'Default value'
do_something(s)
with truthy it is shorter too
s or (s := 'Default value')
do_something(s)
or even shorter,
do_something(s or (s := 'Default value'))
Without the assignment expression, one can do
s = s or 'Default value'
do_something(s)
but not shorter. Some people find the s =... line unsatisfactory because it corresponds to
if len(s)>0:
s = s # HERE is an extra useless assignment
else:
s = "Default value"
nevertheless you can adhere to this coding style if you feel comfortable with it.
Any object in Python can be tested for its truth value. It can be used in an if or while condition or as operand of the Boolean operations.
The following values are considered False:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.
All other values are considered True -- thus objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated.
In case of if (!id) {}
!expr returns false if its single operand can be converted to true; otherwise, returns true.
If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null;
NaN;
0;
empty string ("" or '' or ``);
undefined.
Even though the ! operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.
Example:
n1 = !null // !t returns true
n2 = !NaN // !f returns true
n3 = !'' // !f returns true
n4 = !'Cat' // !t returns false
While in case of if (id != null) {} it will only check if the value in id is not equal to null
reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT
Falsy means something empty like empty list,tuple, as any datatype having empty values or None.
Truthy means :
Except are Truthy
I have a code that checks if a given list of integers can sum up to a specified target. If any combination of the integers in a list can sum up to a target value, it returns True. The input 'start' is the index of the list that I want to start from and continue until the end of the list
def groupSum(start, nums, target):
if start >= len(nums):
return target == 0
else:
return groupSum(start + 1, nums, target - nums[start]) or groupSum(start + 1, nums, target);
So, if I put
groupSum(0, [2,4,8], 10)
it will return True, and, if I put
groupSum(0, [2,4,8], 9)
it will return False
QUESTION: I don't understand how they can put 'or' in the return statements, in a recursive case. I don't see how that's actually working. Is it passing multiple functions simultaneously to check every combination or what?
I'm pretty new to Recursion method and would appreciate it if you can explain the technique used here. Thanks
In python and and or operators, do not return boolean values. They return the last thing evaluated. So, when you
return a or b
if a is a truthy value, a will be returned. Otherwise, the truthness of the expression depends on b, and so b will be returned.
Why it's True for 10 is because there's an exact match for 10 (8+2); which your recursive function reduces to 0 for the target variable.
So, groupSum(start + 1, nums, target - nums[start]) this becomes True - so the comparison will be True or False, which will turn out to True!
Now, for the value of 9, there's no such match and hence it'll always remain False.
You can try for 12 and 6 as well. It'll return True.
Whereas, for any other value the comparison will always be False or False.
I'm going through Zed's "Learn Python The Hard Way" and I'm on ex49. I'm quite confused by the following code he gives:
def peek(word_list):
if word_list: # this gives me trouble
word = word_list[0]
return word[0]
else:
return None
The condition of the if statement is giving me trouble, as commented. I'm not sure what this means as word_list is an object, not a conditional statement. How can word_list, just by itself, follow if?
The if statement applies the built-in bool() function to the expression which follows. In your case, the code-block inside the if statement only runs if bool(word_list) is True.
Different objects in Python evaluate to either True or False in a Boolean context. These objects are considered to be 'Truthy' or 'Falsy'. For example:
In [180]: bool('abc')
Out[180]: True
In [181]: bool('')
Out[181]: False
In [182]: bool([1, 2, 4])
Out[182]: True
In [183]: bool([])
Out[183]: False
In [184]: bool(None)
Out[184]: False
The above are examples of the fact that:
strings of length >= 1 are Truthy.
empty strings are Falsy.
lists of length >= 1 are Truthy.
empty lists are Falsy.
None is Falsy.
So: if word_list will evaluate to True if it is a non-empty list. However, if it is an empty list or None it will evaluate to False.
He is checking if word_list is empty or not. If a list is empty and it is used in a conditional statement, it is evaluated to False. Otherwise, it is evaluated to True.
word_list = ['some value']
if word_list:
# list is not empty do some stuff
print "I WILL PRINT"
word_list = []
if word_list:
# list is empty
print "I WILL NOT PRINT"
In the above code, only the first snippet will print.
See the following reference: https://docs.python.org/2/library/stdtypes.html#truth-value-testing
word_list is a list and when you use it for an if statement condition you check word_list is empty or not :
word_list = []
bool(word_list) # False
if word_list :
print "I'm not empty" # would not printed
word_list = ['a']
bool(word_list) # True
if word_list :
print word_list[0] # 'a'
as Mad Physicist said even None elements in a list means that it's not empty:
word_list = [None]
bool(word_list) # True
What is required for an if block is just something that can be evaluated either to True or to False. A conditional evaluates directly to one of those, but there are other objects that can be converted. To see what any given object is, you can use bool:
>>> mylist = []
>>> bool(mylist)
False
>>> mylist = [4, 3, 6]
>>> bool(mylist)
True
You see, a list is False if it is empty, but True otherwise. Therefore, the if word_list: block will be evaluated if word_list is nonempty. Strings also are False if they are empty, but True otherwise. Same thing with tuples, dictionaries, sets. With numbers, 0 and 0.0 are False, but any other number is True. A fairly common argument to give to indicate to the function to come up with its own value is None which evaluates to False, so the if not mylist: block will be executed if mylist is empty or if mylist is None. (It would also be executed if mylist is 0, (), {}, etc.; but it's unlikely that mylist would be given those)
Take a look at this docs page for Truth Value Testing in python. You should get clear idea about your situation after reading this. Here is the relevant part for easy access.
5.1. Truth Value Testing
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:
None
False
zero of any numeric type, for example, 0, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __bool__()
or __len__() method, when that method returns the integer zero or bool
value False.
All other values are considered true — so objects of many types are always true.
Read the first sentence (bolded) again, and note the bolded parts in the fourth rule. This relates to your question.
So, according to the 4th rule, if your word_list is empty, the condition evaluates to False, otherwise it evaluates to True.
I know you trust in the docs, but here is a code snippet to actually test the truth values for yourself. (I know it is needless to do something like this, but I am always tempted to see things with my own eyes)
def test_truth_value(arg):
# ANY object can be evaluated for truth or false in python
if arg: # or to be more verbose "if arg is True"
print("'{}' is True".format(arg))
else:
print("'{}' is False".format(arg))
class dummy_length_zero():
def __len__(self):
return 0
def __str__(self):
return 'instance of class: "dummy_length_zero"'
class dummy_bool_False():
def __bool__(self):
return False
def __str__(self):
return 'instance of class: "dummy_bool_False"'
obj_dummy_0 = dummy_length_zero()
obj_dummy_false = dummy_bool_False()
args = [None, False, 0, 0.0, 0j, '', (), [], {}, obj_dummy_0, obj_dummy_false]
for arg in args:
test_truth_value(arg)
And lastly, to test that last statement so objects of many types are always true, just remove the implementation of __len__() or __bool__() method from dummy_length_zero or dummy_bool_False class respectively, and check for truth.
In python, everything has an implicit boolean value. Putting any object in an if statement directly is equivalent (but more Pythonic than) doing if bool(word_list):. None, empty sequences, empty sets, empty dicts, 0, False, 0.0 all evaluate to False. Most other objects evaluate to True. That makes if word_list: the most Pythonic way of ensuring that the list is not None or empty before accessing the first element. The long way of expressing the same thing would be if word_list is not None and len(word_list) > 0:.
In Python, every expression can be evaluated to a boolean value (i.e. either True or False).
The following, basic, expressions evaluate to False
The keyword False (obviously!)
The keyword None
The number 0 (0, 0.0 ... )
empty sequence (tuple, list, string)
empty mapping (dictionary)
All other expressions evaluate to True.
So, what the if statement does is evaluating the expression that follows the if keyword to either True or False, then act accordingly.
So in your specific example, if word_list matches any of the above cases it will be considered False, otherwise, it will be considered True.
[#] reference
I was looking for a way to write code that checks whether a certain string is a part of another string. I understand that it is easy to do when we have numbers, but I don't know how to do it with strings.
For example, I have this function
a = is_part("motherland", "land")
I need to know that "land" is a part of the word "motherland" (return True or False). Is it possible to check this?
UPDATE: How can I create a restriction when the second word always has to be in the end of the first one. For example, in case when I check whether "eight" is a part of "eighteen" it returns False because "eight" is not at the end of the first word
This should help:
>>> "land" in "motherland"
True
>>> "banana" in "motherland"
False
Here is a function that determines whether a string target is contained within another string some_string.
def is_part(some_string, target):
return target in some_string
>>> is_part('motherland', 'land')
True
>>> is_part('motherland', 'father')
False
>>> is_part('motherland', '')
True
If you don't like an empty string returning true, change the return statement to
return (target in some_string) if target else False
If, on the other hand, you need to implement it yourself:
def is_part(some_string, target):
if target:
target_len = len(target)
for i in range(len(some_string)):
if some_string[i:i+target_len] == target:
return True
return False
First off, this IS homework, so I am not expecting any direct answers. I need to take two strings defined by a function (semordnilap(str1, str2)) and I need to see if they are equal when one is reversed. I was wondering if I can call these separately out of the function with semordnilap(str1[0:1) == semordnilap(str2[-1]) I tried this a few ways and I must not be thinking about it correctly, plus of course there is the kicker of trying to do this recursively. Any advise or direction would be helpful.
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap
False otherwise.
'''
if len(str1) != len(str2):
return False
if len(str1) <= 1 or len(str2) <= 1:
return False
if semordnilap(str1[0]) != semordnilap(str2[-1]):
return False
else:
return True
This is what I have so far, getting error of TypeError: semordnilap() takes exactly 2 arguments (1 given)
Given two strings str1 and str2, the easiest way to compare if one is equal to the reverse of the other is by using slicing:
str1 = 'racecar'
str2 = 'racecar'
str1 == str2[::-1]
Out[57]: True
Which is really just checking if str1 is a palindrome (i.e. a reverse of itself).
If you really want to use recursion, you also want to be using slicing: check if str1[0] == str2[-1], and then recursively call your function on str1[1:] and str2[:-1].
The [::-1] syntax is extended slicing syntax, which is valid for strings as well as lists and other sequences.
To reverse a string you use 'this is a string'[::-1].
[::-1] Is slice notation which says include everything from the start to the end of the string but do it in reverse.
'abcdefghijk'[6:1:-2] outputs 'gec' because it goes from the 6th index (starting with 0) up to but not including the first index, in reverse steps of 2.
Read up more on slice notation:Explain Python's slice notation, http://docs.python.org/2.3/whatsnew/section-slices.html
def semordnilap(str1, str2):
if str1 == str2[::-1]: return True
else: return False
One way to do it recursively:
def semordnilap(str1, str2):
if not (len(str1) or len(str2)): return True
if not (len(str1) and len(str2)): return False
if str1[0] != str2[-1]: return False
return semordnilap(str1[1:], str2[:-1])
The first line checks if both strings are empty (0 evaluates to False, any other number is True). len(str1) returns the length as an integer.
Then it checks if only one of the strings is empty in which case they are not equal.
Then it checks if the first letter is the same as the last letter.
Then it repeats the process with the each string (minus the first letter of str1 and minus the last letter of str2). It goes until one of the base cases is reached. The base case is what is returned. So it will only return True when then first letter was equal to the last letter each round until both strings ran out of characters at the same time.