I have a problem that states: Write a function that takes, as an argument, a list and a string,and returns a Boolean based on whether or not all of the letters in the string appear somewhere in the list. Here is what I have so far.
def findLetters(myList, myString):
for letter in myString:
if letter in myList:
return True
return False
Here's a basic solution that's closer to what you've started:
def findLetters(myList, myString):
found_all = False
for s in myString: # check each letter in the string
if s in myList: # see if it is in the list
found_all = True # keep going if found
else:
found_all = False # otherwise set `found` to False
break # and break out of the loop
return found_all # return the result
result = findLetters(['a', 'l', 'i', 's', 't'], 'mlist')
# 'm' is not in the list
print result # False
# all letters in the string are in the list;
# ignores any extra characters in the list that are not in the string
result = findLetters(['a', 'l', 'i', 's', 't', 'p'], 'alist')
print result # True
You can map all letters using a lambda which creates a list of boolean values for all letters in my_string.
The function all returns true if all values in the l list ar True.
def find_letters(my_list, my_string):
l = map(lambda x: x in my_list, my_string)
return all(l)
print(find_letters(['a', 'b', 'c'], 'cab'))
you are returning True if any letter match in myString, not all letter in myString.
You could do the other way around, if any letter not match in myString, return False
def findLetters(myList, myString):
for letter in myString:
if letter not in myList:
return False
return True
OR use builtin function all
def findLetters(myList, myString):
return all(letter in myList for letter in myString)
Related
Define a function convert(input str) to return a list of characters based on the input
string input str. Specifically, each character in input str will be included as a separate element of
the returned list, while any spaces in input str will be ignored
def convert(input_str):
newlist = []
reallist = [char for char in input_str]
for k in input_str:
if k:
newlist.append(k)
return newlist
print(convert("Hi You"))
this gives output
['H', 'i', ' ', 'Y', 'o', 'u']
but I do not want the empty space between i and y
Instead of using a list comprehension and then filter the resulting list, you can do it in one step using if in the list comprehension:
def convert(input_str: str):
return [c for c in input_str if not c.isspace()]
print(convert("Hi You")) # ['H', 'i', 'Y', 'o', 'u']
Instead of using isspace, you could use [c for c in input_str if c != ' '] instead (although I believe using isspace is generally recommended).
you just need to add an if statement before you append an item to the list, only if char != " ": append char to new_list
def convert(input_str):
new_list = []
for char in input_str:
if char != " ": # <-----
new_list.append(char)
return new_list
print(convert("Hi You"))
def convert(input_str):
newstr = "".join(input_str.split())
reallist = [char for char in newstr]
return reallist
print(convert("Hi You"))
Maybe this if it is not just one space you are trying to skip
Python has built-in method for string that replaces string inside of string with another string. It takes the character that you want to replace and with what you want to replace it with as arguments.
def convert(input_str):
# Replace whitespaces with nothing
input_str = input_str.replace(" ", "")
new_list = [char for char in input_str]
return new_list
print(convert("Hi You"))
word represents the string I am checking, letters is a list of random letters. I need to make sure that the word only contains letters in a list. However if their are repeating letters, there needs to be that many repeating letters in the list. If returned True it needs to remove the letters used in the word from the list. I am really struggling with this one.
example: w.wordcheck('feed') -> False
letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
w.wordcheck('gag') -> false
w.wordcheck('gene') -> True
w.wordcheck('gene') -> True
print(letters) -> ['f', 'a', 'z']
letters = []
def wordcheck(self, word)
for char in word:
if char not in self.letters:
return False
else:
return True
One way using collections.Counter:
from collections import Counter
letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
cnt = Counter(letters)
def wordcheck(word):
return all(cnt[k] - v >= 0 for k, v in Counter(word).items())
Output:
wordcheck("gag")
# False
wordcheck("gene")
# True
You can do solve , this problem by finding the case where word result into false.
these cases are, when the character is not in the letters and character frequency in word is more than the character frequency in the letter.
once if any of condition meet, return false else return true.
# your code goes here
from collections import Counter
letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
letters_count = Counter(letters)
def func(word):
word_count = Counter(word)
check = True
for word in word_count:
if word not in letters_count or word_count.get(word)>letters_count.get(word):
check = False
break
return check
l = ['feed', 'gag', 'gene']
for i in l:
print(func(i))
output
False
False
True
There are already better answers, but I felt like adding a novel solution just for the heck of it:
from itertools import groupby
def chunks(s):
return set("".join(g) for _, g in groupby(sorted(s)))
def wordcheck(word, valid_letters):
return chunks(word) <= chunks(valid_letters)
Steps:
Turn word into a set of chunks, e.g.: "gag" -> {"a", "gg"}
Turn valid_letters into a set of chunks
Check if word is a subset of valid_letters
Limitations:
This is a mostly silly implementation
This will only return True if the exact number of repeated letters is present in valid_letters, e.g.: if valid_letters = "ccc" and word = "cc" this will return False because there are too few c's in word
It's really inefficient
Please this function:
def foo(string):
for char in string:
if char != 'h' and char != 'a':
return False
return True
So i want to write this function in one line and this is what i have try:
def foo(string):
return [True if 'a' or 'h' in x else False for x in string]
Your function checks whether the string consists of only the characters 'a' and 'h', so it can be replaced with a test to see whether the set of its characters is a subset of {'a', 'h'}.
def foo(string):
return set(string) <= {'a', 'h'}
Your one liner does not what you think it does.
let's decompose your function:
[x for x in string]
will return a list of strings:
>>> string = "aoeu"
>>> [x for x in string]
['a', 'o', 'e', 'u']
so then you apply:
if 'a' or 'h' in x
for each x in the above list, let's decompose that:
>>> slist = [x for x in string]
>>> 'a' or 'h' in slist[0]
'a'
Here what you do is check if 'a' exists (and it does and always will be) or check if 'h' is within the single char string slist[0]. Though the second part never gets valued, as 'a' is always there.
So to fix this you want:
>>> 'a' == slist[0] or 'h' in slist[0]
True
or more concise:
>>> slist[0] in ['a', 'h']
True
So to rebuild your one-liner:
>>> [True if c in ['a', 'h'] else False for c in string]
[True, False, False, False]
But as you see, that returns a list, so you want to have one value in the end
>>> any([True if c in ['a', 'h'] else False for c in string])
True
So your function would be:
def foo(string):
return any([True if c in ['a', 'h'] else False for c in string])
So now, what we've built is a function that says whether there's a 'a' or 'h' in the string. In a long and complex way, that could be rewritten:
def foo(string):
return "a" in string or "b" in string
But... that's not what your first function does!
def foo(string):
for char in string:
if char != 'h' and char != 'a':
return False
return True
that one checks whether the string is only made of 'a' or 'h'.
so the best way is to turn your string into a set, to see all the different characters it contains, and return whether that set equal to the set of only 'a' and 'h'.
Others have been faster than me to come up with the solution, so here it goes:
def foo(string):
return set(string) <= {'a', 'h'}
thanks to #kaya3 which gave the most elegant solution ;)
You can use sets to see if string contains anything other than 'a' or 'h'
return not (set(string) - {'a', 'h'})
I'm pretty sure my code is correct but it doesn't seem to returning the expected output:
input anti_vowel("Hey look words") --> outputs: "Hey lk wrds".
Apparently it's not working on the 'e', can anyone explain why?
def anti_vowel(c):
newstr = ""
vowels = ('a', 'e', 'i', 'o', 'u')
for x in c.lower():
if x in vowels:
newstr = c.replace(x, "")
return newstr
The function str.replace(old, new[, max]) don't changes c string itself (wrt to c you calls) just returns a new string which the occurrences of old have been replaced with new. So newstr just contains a string replaced by last vowel in c string that is the o and hence you are getting "Hey lk wrds" that is same as "Hey look words".replace('o', '').
I think you can simply write anti_vowel(c) as:
''.join([l for l in c if l not in vowels]);
What I am doing is iterating over string and if a letter is not a vowel then only include it into list(filters). After filtering I join back list as a string.
Why don't you do it with regexp? According to the documentation, something like this should work:
import re
def anti_vowel(s):
result = re.sub(r'[AEIOU]', '', s, flags=re.IGNORECASE)
return result
If you're using the function often, you could compile the regexp and use the compiled version.
Try String.translate.
>>> "Hey look words".translate(None, 'aeiouAEIOU')
'Hy lk wrds'
string.translate(s, table[, deletechars])
Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
https://docs.python.org/2/library/string.html#string.Template.substitute
Or if you're using the newfangled Python 3:
>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words.translate(table)
'Hy lk wrds'
Another option is to forego the vowel variable and put the char's to remove in the loop.
def anti_vowel(text):
for i in "aeiouAEIOU":
text = text.replace(i,"")
return text
print anti_vowel("HappIEAOy")
You should do this:
initialize newstr to c, and then
for x in c.lower():
if x in vowels:
newstr = newstr.replace(x, "")
That's because str.replace(old, new[, max]) returns the a copy of the string after replacing the characters:
The method replace() returns a copy of the string in which the
occurrences of old have been replaced with new, optionally restricting
the number of replacements to max.
So, this is the correct code:
def anti_vowel(c):
newstr = c
vowels = ('a', 'e', 'i', 'o', 'u')
for x in c.lower():
if x in vowels:
newstr = newstr.replace(x,"")
return newstr
You can also do it in a more pythonic way:
''.join([x for x in c if x not in vowels])
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'I', 'E', 'O', 'U')
for char in text:
if char in vowels:
text = text.replace(char, '')
return text
One more simpler way can be extracting the non-vowel characters from string and returning them.
def anti_vowel(text):
newstring=""
for i in text:
if i not in "aeiouAEIOU":
newstring=newstring+i
text=newstring
return text
I know there are many correct solutions on this subject but I thought to add few fun ways of solving this problem.
If you come from a C++/C# or Java, you will tend to use something like compare then action using the index to remove the unwanted entry in a for loop. Python has the Remove and Del functions. Remove function uses the value and
del uses the index.The pythonic solution is in the last function. Lets see how we can do that:
Here we are using the index in a for loop and del function very similar in C++:
def remove_vol(str1):
#list2 = list1 # this won't work bc list1 is the same as list2 meaning same container#
list1 = list(str1)
list2 = list(str1)
for i in range(len(list1)):
if list1[i] in volwes:
vol = list1[i]
x = list2.index(vol)
del list2[x]
print(list2)
Using the remove function:
def remove_vol(str1):
list1 = list(str1)
list2 = list(str1)
for i in list1:
if i in volwes:
list2.remove(i)
print(list2)
Building new string that does not contain the unwanted chars using their indexes:
def remove_vol(str1):
list1 = list(str1)
clean_str = ''
for i in range(len(list1)):
if list1[i] not in volwes:
clean_str += ''.join(list1[i])
print(clean_str)
Same as in the solution in above but using the value:
def remove_vol(str1):
list1 = list(str1)
clean_str = ''
for i in list1:
if i not in volwes:
clean_str += ''.join(i)
print(clean_str)
How you should do it in python? Using list comprehension! It is beautiful:
def remove_vol(list1):
clean_str = ''.join([x for x in list1 if x.lower() not in volwes])
print(clean_str)
def anti_vowel(text):
new=[]
vowels = ("aeiouAEIOU")
for i in text:
if i not in vowels:
new.append(i)
return ''.join(new)
i hope this helps..
def anti_vowel(text):
new_text = ""
for i in text:
if i == 'a' or i == 'A':
pass
elif i == 'e' or i == 'E':
pass
elif i == 'I' or i == 'i':
pass
elif i == 'o' or i == 'O':
pass
elif i == 'u' or i == 'U':
pass
else:
new_text = new_text + i
return new_text
print anti_vowel('Hey look Words!')
My implementation:
# Ask the user for input:
user_input = input("enter a string with some vowels: ")
print("input string: " + str(user_input))
vowels = ('a','e','i','o','u','A','E','I','O','U')
new_string="";
for i in range(0,len(user_input),1):
if user_input[i] in vowels:
print ('found a vowel, removing...')
else:
new_string+=user_input[i]
print("I've removed the vowels for you. You're welcome! The new string is: " + new_string)
A fairly simple approach could be;
def anti_vowel(text):
t = ''
for c in text:
if c in "aeiouAEIOU":
pass
else:
t += c
return t
def anti_vowel(text):
t=""
for c in text:
for i in "ieaouIEAOU":
if c==i:
c=""
else:
c=c
t=t+c
return t
I'm pretty sure my code is correct but it doesn't seem to returning the expected output:
input anti_vowel("Hey look words") --> outputs: "Hey lk wrds".
Apparently it's not working on the 'e', can anyone explain why?
def anti_vowel(c):
newstr = ""
vowels = ('a', 'e', 'i', 'o', 'u')
for x in c.lower():
if x in vowels:
newstr = c.replace(x, "")
return newstr
The function str.replace(old, new[, max]) don't changes c string itself (wrt to c you calls) just returns a new string which the occurrences of old have been replaced with new. So newstr just contains a string replaced by last vowel in c string that is the o and hence you are getting "Hey lk wrds" that is same as "Hey look words".replace('o', '').
I think you can simply write anti_vowel(c) as:
''.join([l for l in c if l not in vowels]);
What I am doing is iterating over string and if a letter is not a vowel then only include it into list(filters). After filtering I join back list as a string.
Why don't you do it with regexp? According to the documentation, something like this should work:
import re
def anti_vowel(s):
result = re.sub(r'[AEIOU]', '', s, flags=re.IGNORECASE)
return result
If you're using the function often, you could compile the regexp and use the compiled version.
Try String.translate.
>>> "Hey look words".translate(None, 'aeiouAEIOU')
'Hy lk wrds'
string.translate(s, table[, deletechars])
Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
https://docs.python.org/2/library/string.html#string.Template.substitute
Or if you're using the newfangled Python 3:
>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words.translate(table)
'Hy lk wrds'
Another option is to forego the vowel variable and put the char's to remove in the loop.
def anti_vowel(text):
for i in "aeiouAEIOU":
text = text.replace(i,"")
return text
print anti_vowel("HappIEAOy")
You should do this:
initialize newstr to c, and then
for x in c.lower():
if x in vowels:
newstr = newstr.replace(x, "")
That's because str.replace(old, new[, max]) returns the a copy of the string after replacing the characters:
The method replace() returns a copy of the string in which the
occurrences of old have been replaced with new, optionally restricting
the number of replacements to max.
So, this is the correct code:
def anti_vowel(c):
newstr = c
vowels = ('a', 'e', 'i', 'o', 'u')
for x in c.lower():
if x in vowels:
newstr = newstr.replace(x,"")
return newstr
You can also do it in a more pythonic way:
''.join([x for x in c if x not in vowels])
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'I', 'E', 'O', 'U')
for char in text:
if char in vowels:
text = text.replace(char, '')
return text
One more simpler way can be extracting the non-vowel characters from string and returning them.
def anti_vowel(text):
newstring=""
for i in text:
if i not in "aeiouAEIOU":
newstring=newstring+i
text=newstring
return text
I know there are many correct solutions on this subject but I thought to add few fun ways of solving this problem.
If you come from a C++/C# or Java, you will tend to use something like compare then action using the index to remove the unwanted entry in a for loop. Python has the Remove and Del functions. Remove function uses the value and
del uses the index.The pythonic solution is in the last function. Lets see how we can do that:
Here we are using the index in a for loop and del function very similar in C++:
def remove_vol(str1):
#list2 = list1 # this won't work bc list1 is the same as list2 meaning same container#
list1 = list(str1)
list2 = list(str1)
for i in range(len(list1)):
if list1[i] in volwes:
vol = list1[i]
x = list2.index(vol)
del list2[x]
print(list2)
Using the remove function:
def remove_vol(str1):
list1 = list(str1)
list2 = list(str1)
for i in list1:
if i in volwes:
list2.remove(i)
print(list2)
Building new string that does not contain the unwanted chars using their indexes:
def remove_vol(str1):
list1 = list(str1)
clean_str = ''
for i in range(len(list1)):
if list1[i] not in volwes:
clean_str += ''.join(list1[i])
print(clean_str)
Same as in the solution in above but using the value:
def remove_vol(str1):
list1 = list(str1)
clean_str = ''
for i in list1:
if i not in volwes:
clean_str += ''.join(i)
print(clean_str)
How you should do it in python? Using list comprehension! It is beautiful:
def remove_vol(list1):
clean_str = ''.join([x for x in list1 if x.lower() not in volwes])
print(clean_str)
def anti_vowel(text):
new=[]
vowels = ("aeiouAEIOU")
for i in text:
if i not in vowels:
new.append(i)
return ''.join(new)
i hope this helps..
def anti_vowel(text):
new_text = ""
for i in text:
if i == 'a' or i == 'A':
pass
elif i == 'e' or i == 'E':
pass
elif i == 'I' or i == 'i':
pass
elif i == 'o' or i == 'O':
pass
elif i == 'u' or i == 'U':
pass
else:
new_text = new_text + i
return new_text
print anti_vowel('Hey look Words!')
My implementation:
# Ask the user for input:
user_input = input("enter a string with some vowels: ")
print("input string: " + str(user_input))
vowels = ('a','e','i','o','u','A','E','I','O','U')
new_string="";
for i in range(0,len(user_input),1):
if user_input[i] in vowels:
print ('found a vowel, removing...')
else:
new_string+=user_input[i]
print("I've removed the vowels for you. You're welcome! The new string is: " + new_string)
A fairly simple approach could be;
def anti_vowel(text):
t = ''
for c in text:
if c in "aeiouAEIOU":
pass
else:
t += c
return t
def anti_vowel(text):
t=""
for c in text:
for i in "ieaouIEAOU":
if c==i:
c=""
else:
c=c
t=t+c
return t