How can i test if multiple strings exist in another list? Below is a code example that I started with but doesn't work properly. It should return true if even part of the string is found in the list.
I marked in the comments what the result should return. as you can see they all fail though.
def all_exist(avalue, bvalue):
if avalue == []:
return True
else:
print (all(x in avalue for x in bvalue))
items = ['greg','krista','marie']
all_exist(['greg', 'krista'], items) # true
all_exist(['gre', 'kris'], items) # true
all_exist(['gre', 'purple'], items) # false
Would it be better to convert the second list to a single string and then just test if strings in list exist in it?
You have to check if all of the strings in the first list is contained by any string in the second list:
def all_exist(avalue, bvalue):
return all(any(x in y for y in bvalue) for x in avalue)
items = ['greg','krista','marie']
print(all_exist(['greg', 'krista'], items)) # -> True
print(all_exist(['gre', 'kris'], items)) # -> True
print(all_exist(['gre', 'purple'], items)) # -> False
print(all_exist([], items)) # -> True
We want to loop through the elements in avalue and check if this element is in any of the strings in bvalue. But we want to do all of that inside all as we want to check that all elements in avalue have a match.
Also, if we do the test this way, an empty avalue will return True anyway, so we don't need to tell Python to explicitly do this.
Note that: since you have defined all_exist as a function, it should really return a value, not print the result, so I have changed that for you:
def all_exist(avalue, bvalue):
return all(any(i in j for j in bvalue) for i in avalue)
and some testing shows it works:
>>> all_exist(['greg', 'krista'], items) # true
True
>>> all_exist(['gre', 'kris'], items) # true
True
>>> all_exist(['gre', 'purple'], items) # false
False
Related
how to check if this list is empty?
l = ['',['']]
I tried solutions from how to find if nested lists are empty. but none of them worked.
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
return all( map(isListEmpty, inList) )
return False # Not a list
You should check if the list is falsy/empty first before recursively checking the list items. You can also avoid explicitly returning True or False by using the and and or operators:
def isListEmpty(inList):
return inList == '' or isinstance(inList, list) and (not inList or all(map(isListEmpty, inList)))
Demo: https://repl.it/repls/AccurateSmallOutcome
For lists that actually are empty, the function should simply return True.
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
if len(inList) == 0:
return True
else:
return all(map(isListEmpty, inList))
return False # Not a list
l is not empty in fact. But in this case this code should work:
l = ['',['']]
def isListEmpty(inList):
for char in inList:
if char == '' or ['']:
return True
else:
return False
break
print(isListEmpty(l))
You can use a simple recursive approach with any. Using any would make sure that the recursively search ends as soon as a non empty item is found
>>> def is_non_empty_list (l):
... return any(is_non_empty_list(e) if isinstance(e, list) else e for e in l)
...
>>> def is_empty_list (l):
... return not is_non_empty_list(l)
...
>>> is_empty_list(['', ['']])
True
>>> is_empty_list(['', ['a']])
False
>>>
Try This
l = [' ',[ ]]
def isListEmpty(thisList):
for el in thisList:
if (len(el)==0 and type(el)==list):
print('empty') # Or whatever you want to do if you encounter an empty list
isListEmpty(l)
If you face any problems comment below
There aren't a set of instructions, but I basically have to write a code for def hasNoDuplicate and it returns True exactly when list has no duplicates. This is what I've written, I'm new to programming so all of this is very overwhelming. I don't know exactly what to put in the if statement. Any advice would help a lot!
def hasNoDuplicates(values):
foundCounterExampleYet = False
for value in values:
if():
foundCounterExampleYet = True
return not(foundCounterExampleYet)
def hasNoDuplicates(values):
foundCounterExampleYet = False
value = None
while values:
value = values.pop()
if value in values:
foundCounterExampleYet = True
break
return not(foundCounterExampleYet)
Now you get:
>>> hasNoDuplicates([1,2,3])
True
>>> hasNoDuplicates([1,2,3,4,6,7,8,9,4])
False
>>>
What this code does is, it takes the input list, and one by one takes out the last element from the list and checks if the item exists in the list. If it exists, then a duplication is detected, and it changes the value of foundCounterExampleYet and consequently jumps out of the loop. This checking happens until the list becomes empty. while values means do this while the list is not empty
The pop method takes out the last element from the list. But it has side effect, meaning it changes the value of the initial input:
>>> [1,2,3].pop()
3
>>> a = [1,2,3]
>>> a.pop()
3
>>> a
[1, 2]
You're on the right track. You can store the values in a set as you're looping through the inputs, and use the in operator to check for membership in that set. See my comments alongside the following code.
def hasNoDuplicates(values):
currentValues = set() # initialize an empty set
for value in values: # iterate over your inputs
if value in currentValues: # if the current value is in your set, there is a duplicate
return False
else:
currentValues.add(value) # no duplicate exists, add it to the set
return True # If it made it through all the values, there were no duplicates
For fun, there is an easier way to do this. If the items in the values sequence are hashable, you can make a set from the whole sequence. Since by definition a set may not have any duplicates, if the length of the original sequence is the same length as the set, then all items are unique. If the set is shorter, there was at least one duplicate.
def hasNoDuplicates(values):
return len(values) == len(set(values))
I'm working with this exercise:
Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)
I wrote this function:
def isMember(value, list):
for element in list:
if(element == value):
return True
else:
return False
myList = ["a","b","c",1,2,3]
print(isMember("a",myList)) #Returns True; correct
print(isMember(3,myList)) #Returns False; why the heck?
You need to take the return False out of the loop:
def isMember(value, list):
for element in list:
if(element == value):
return True
return False
The way you have it currently, isMember will return False if the value is not the first item in the list. Also, you should change the name of your list variable to something other than list, which is a built-in function in Python.
The problem is that your return False is within the loop, directly as the else case of your membership test. So as you loop through the list, you get to the first element and check if it is in the list or not. If it is in the list, you return true—that’s fine. If it’s not in the list, you return false, aborting the loop process and ending the function. So you never look at the other values inside the loop.
So to fix this, move the return False outside of the loop, at the end of the function. That way, only when all elements have been looked at, you return false.
def isMember (value, list):
for element in list:
if element == value:
return True
return False
Another way would be to simplify this using the any function to perform the check for every element in the list. any takes an iterable and looks at the values. As soon as it finds a true value, it returns true. Otherwise it keeps iterating until it finds a false value or hits the end of the iterator, both cases yielding a false. So you could rewrite it like this:
def isMember (value, list):
return any(value == element for element in list)
I have written a function to check for the existence of a value in a list and return True if it exists. It works well for exact matches, but I need for it to return True if the value exists anywhere in the list entry (e.g. value <= listEntry, I think.) Here is the code I am using for the function:
def isValInLst(val,lst):
"""check to see if val is in lst. If it doesn't NOT exist (i.e. != 0),
return True. Otherwise return false."""
if lst.count(val) != 0:
return True
else:
print 'val is '+str(val)
return False
Without looping through the entire character string and/or using RegEx's (unless those are the most efficient), how should I go about this in a pythonic manner?
This is very similar to another SO question, but I need to check for the existence of the ENTIRE val string anywhere in the list. It would also be great to return the index / indices of matches, but I'm sure that's covered elsewhere on Stackoverflow.
If I understood your question then I guess you need any:
return any(val in x for x in lst)
Demo:
>>> lst = ['aaa','dfbbsd','sdfdee']
>>> val = 'bb'
>>> any(val in x for x in lst)
True
>>> val = "foo"
>>> any(val in x for x in lst)
False
>>> val = "fde"
>>> any(val in x for x in lst)
True
Mostly covered, but if you want to get the index of the matches I would suggest something like this:
indices = [index for index, content in enumerate(input) if substring in content]
if you want to add in the true/false you can still directly use the result from this list comprehension since it will return an empty list if your input doesn't contain the substring which will evaluate to False.
In the terms of your first function:
def isValInLst(val, lst):
return bool([index for index, content in enumerate(lst) if val in content])
where the bool() just converts the answer into a boolean value, but without the bool this will return a list of all places where the substring appears in the list.
There are multiple possibilities to do that. For example:
def valInList1 (val, lst):
# check `in` for each element in the list
return any(val in x for x in lst)
def valInList2 (val, lst):
# join the list to a single string using some character
# that definitely does not occur in val
return val in ';;;'.join(lst)
How can I find out if a list is empty without using the not command?
Here is what I tried:
if list3[0] == []:
print("No matches found")
else:
print(list3)
I am very much a beginner so excuse me if I do dumb mistakes.
In order of preference:
# Good
if not list3:
# Okay
if len(list3) == 0:
# Ugly
if list3 == []:
# Silly
try:
next(iter(list3))
# list has elements
except StopIteration:
# list is empty
If you have both an if and an else you might also re-order the cases:
if list3:
# list has elements
else:
# list is empty
You find out if a list is empty by testing the 'truth' of it:
>>> bool([])
False
>>> bool([0])
True
While in the second case 0 is False, but the list [0] is True because it contains something. (If you want to test a list for containing all falsey things, use all or any: any(e for e in li) is True if any item in li is truthy.)
This results in this idiom:
if li:
# li has something in it
else:
# optional else -- li does not have something
if not li:
# react to li being empty
# optional else...
According to PEP 8, this is the proper way:
• For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq)
if not len(seq)
You test if a list has a specific index existing by using try:
>>> try:
... li[3]=6
... except IndexError:
... print 'no bueno'
...
no bueno
So you may want to reverse the order of your code to this:
if list3:
print list3
else:
print "No matches found"
Check its length.
l = []
print len(l) == 0
this is how you would do that
if len(list3) == 0:
print("No matches found")
Python provides an inbuilt any() function to check whether an iterable is empty or not:
>>>list=[]
>>>any(list)
False
The function returns True if the iterable contains a 'True' value, and False otherwise.
However, note that the list [0] also returns False with any().