Given the following lists:
list1 = ["Box", "Stall"]
list2 = ["Ball", "Sox"]
How can I check whether all the chars that make up 'Ball' and 'Sox', ('BallSox') are contained within 'BoxStall' (the chars that make up 'Box' and 'Stall')? Which they are. It has to be case sensitive.
I tried using the list() command within an if statement, checking if all of the chars of the 'Box' are within list2, but it seems like it would have to be a bit more complicated.
I don't think that there is a built-in function that would handle this. What you could do is
# put all characters of first list into a dictionary
# object. This is easier to use for looking up characters
# later
list_chars = {}
for string in list1:
for char in string:
list_chars[char] = True
# run through second list, for each character
# in the other list, check if it exists in
# the dictionary of characters from the first
# list. If it does not, then set missing_character to True.
missing_character = False
for string in list2:
for char in string:
if not list_chars.get(char,False):
# means that the first list does
# not contain the character char
missing_character = True
# print whether one list was actually missing a character.
if missing_character:
print('Missing some character!')
else
print('Contained all characters!')
Feel free to ask a follow up question if some part of the above doesn't make sense. Also, you could make the above code a little faster if you use break statements above. (Exit the for loops early if you already know that the list is missing a character.) I'll leave that for you to reason through and figure out if you're interested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With