How to simplify the IF statement in Python 3 - python

I have the IF statement as follows:
...
if word.endswith('a') or word.endswith('e') or word.endswith('i') or word.endswith('o') or word.endswith('u'):
...
Here I had to use 4 ORs to cover all the circumstances. Is there anyway I can simplify this? I'm using Python 3.4.

Use any
>>> word = 'fa'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>> word = 'fe'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>>

Try
if word[-1] in ['a','e','i','o','u']:
where word[-1] is the last letter

Simply:
>>> "apple"[-1] in 'aeiou'
True
>>> "boy"[-1] in 'aeiou'
False

word.endswith(c) is just the same as word[-1] == c so:
VOWELS = 'aeiou'
if word[-1] in VOWELS:
print('{} ends with a vowel'.format(word)
will do. There is no need to construct a list, tuple, set, or other data structure: just test membership in a string, in this case VOWELS.

Related

Comparing letters in list with string in a list python

I have a list lets say:
DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z']
Now the other parameter of mine is like arguement, I write in
udl and it returns ['udl']
so lets say another list arg_list = ['udl']
I want to check if u and d and l is in this list or i want to check if none of the letters in my direction letters list in the arg list
to make it print error msg I have tried this:
for letter in DIRECTION_LETTERS:
for char in arg_list[4]:
if letter in arg_list[4][0]:
continue
else:
print (ERROR_MESSAGE_DIRECTIONS)
return False
return True
There's a handy function in Python called all() which returns true if all arguments are true. Feel free to find a nice way of using it, but in general:
>>> DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z']
>>>
>>> s="udl"
>>> print(all(c in DIRECTION_LETTERS for c in s))
True
>>> s="udlxa"
>>> print(all(c in DIRECTION_LETTERS for c in s))
False
This line
if letter in arg_list[4][0]:
needs to be
if char in DIRECTION_LETTERS:
and you need to delete the line for letter in DIRECTION_LETTERS:.

When to break up a function

Currently I am very new to python programming, been working on it for a while, I came across a little project task which was to make a program that takes all of the vowels out of a statement so I decided to try it out. I came up with a program but it seems that it only takes out the vowels sometimes, I find this very weird and I would like to ask for some assistance in solving it.
def anti_vowel(text):
list = ['a', 'e', 'i', 'o', 'u']
big_list = ['A', 'E', 'I', 'O', 'U']
list_word = []
for f in text:
list_word.append(f)
for vowel in list:
for letter in list_word:
if vowel == letter:
list_word.remove(vowel)
for vowel in big_list:
for letter in list_word:
if vowel == letter:
list_word.remove(vowel)
new_word = ''.join(list_word)
return new_word
print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")
This statement as it sits prints out 'IiIuUUuoouU', but if I add more iterations over the lists using more for statements it decreases the amount of shown letters. Can someone tell me why this might be?
A little improvement:
list = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
def anti_vowel(text):
return ''.join([x for x in text if x not in list])
print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")
Abend's solution with little edits that make it correct
vowels = ['a','e','i','o','u','A','E','I','O','U']
def no_vowels(str1):
return ''.join([char for char in list(str1) if char not in vowels])
print no_vowels('finished')
Gives
fnshd
Process finished with exit code 0
This code is the correct implementation
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

How to check if a string contains a string from a list?

I want to check if a string the user inputted contains one of the strings in a list.
I know how to check if the string contains one string but I want to know how to check if a string contains either this string, or that string, or another string.
For example, if I am checking the user's input to see if it contains a vowel.. there can be 5 different choices when we're talking about vowels (a, e, i, o, or u). How can I check to see if the string the user inputted has one of those?
Using any:
>>> vowels = 'a', 'e', 'i', 'o', 'u'
>>> s = 'cat'
>>> any(ch in vowels for ch in s)
True
>>> s = 'pyth-n'
>>> any(ch in vowels for ch in s)
False
>>> vowels = set(['a', 'e', 'i', 'o', 'u'])
>>> inp = "foobar"
>>> bool(vowels.intersection(inp))
True
>>> bool(vowels.intersection('qwty'))
False
This is the basic logic you want:
def string_checker(user_input_string, vowels):
for i in vowels:
if i in user_input_string:
return 'Found it'
return 'Sorry grashooper :('
print string_checker('Hello',('a','e','i','o','u'))
The short cut way to do this is by using the built-in any() method; which will return true if any of the items in it returns a truth value.
Here is how it would work:
any(i in user_input_string for i in vowels)
The difference is that instead of returning a custom string, this method will return True or False; we can use it the same way in our loop:
if any(i in user_input_string for i in vowels):
print('Found it!')
else:
print('Oh noes! No vowels for you!')
Checking the strings sequentially works, but if it's too inefficient for your case, you can use Aho-Corasick algorithm.
You can use this syntax
if myItem in list:
# do something
also look at the functions:
http://docs.python.org/2/library/functions.html

Python code that will find words made out of specific letters. Any subset of the letters could be used [duplicate]

This question already has answers here:
In Python, how to check if a string only contains certain characters?
(9 answers)
Closed 7 months ago.
If I have a list of words in the variable words and a list of letters in the variable letters, how can I find all the words that can be made up out of the letters in letters. Any subset of the letters in the variable letters can be used and letters can be used more than once. I would like to do this in Python.
For example:
letters = ['a', 'b', 'i', 'l', 'r', 's', 't', 'u']
words = ['dummy', 'australia']
Should return:
'australia'
even though there is an additional 'b', but not:
'dummy'
since d, m and y are not available.
Use regular expressions:
>>> import re
>>> m = re.compile('^[abilrstu]+$')
>>> m.match('australia') is not None
True
>>> m.match('dummy') is not None
False
>>> m.match('australian') is not None
False
you can use all() along with sets, because they allow O(1) membership checkup:
In [9]: words = ['dummy', 'australia']
In [10]: letters = ['a', 'b', 'i', 'l', 'r', 's', 't', 'u']
In [11]: let_set=set(letters)
In [12]: for word in words:
if all(x in let_set for x in set(word)):
print word
....:
australia
This is probably the easiest way:
result = [w for w in words if all(i in letters for i in w)]
This returns ['australia']
This employs set intersection, which might be faster. On the other hand, it requires additional memory.
letters = ['a', 'b', 'i', 'l', 'r', 's', 't', 'u']
words = ['dummy', 'australia', 'australians' ]
f = set(letters)
c = [ (word, set(word)) for word in words ]
# changing to s & f == f makes condition "must use ALL letters"
s = [ w for (w, s) in c if s & f == s ]
s is now ['australia']
(But I'm curious about the use of such a solution. A Scrabble robot? A dusty-keyboard attack on dictionary passwords? )

how to find special characters in a string

I have a code in Python and want to find vowels in a string.
The code I have written is following....I tried different combinations for using For-Loop, but it throws two different errors;
'int' object is not iterable,
string indices must be integers, not str.
how can I find all vowels in a line?
str1 = 'sator arepo tenet opera rotas'
vow1 = [str1[i] for i in str1 if str1[i] is 'a' | 'e' | 'o']
what about:
vowels = [ c for c in str1 if c in 'aeo' ]
You're getting errors because when you loop over a string, you loop over the characters in the string (not string indices) and because 'a' | 'e' | 'o' doesn't make sense for strings -- (they don't support the | operator)
>>> str1 = 'sator arepo tenet opera rotas'
>>> vowels = [ c for c in str1 if c in 'aeo' ]
>>> print vowels
['a', 'o', 'a', 'e', 'o', 'e', 'e', 'o', 'e', 'a', 'o', 'a']
One final comment, you shouldn't use is to test for equality. is tests for identity. A simple test:
a = 565
b = 565
print a == b #True
print a is b #False (!)
The reason is because a and b reference different objects that have the same value.
Try this code:
str1 = 'sator arepo tenet opera rotas'
i=0
vowl=''
for char in str1:
if char in 'aeiouAEIOU':
vowl=vowl+char+','
vowl=vowl[:-1]
print (vowl)
The output is:
a,o,a,e,o,e,e,o,e,a,o,a
In [1]: str1 = 'sator arepo tenet opera rotas'
In [2]: filter(lambda x: x in 'aeiou', str1)
Out[2]: 'aoaeoeeoeaoa'

Categories

Resources