Python - Check if a word belongs - python

I need your help about a small program I'm making.
The program checks if a word is True, False or invalid argument.
For example, I type e_silaba(ALO) and it verifies if the word is possible based on the letters in vowel.
My first question is, do I have to choose the size of my string (word)?
What better way do I have to see if the word doesn't belong to "vowel"? I know the way I made is wrong but I can't find a solution for that..
The way I made to check if the word is true only verifies the first two positions and I don't think it's a good idea to spam and's all over the place. Is there a way to easily verify each position of the string one by one to check if it belongs to, in this case, "vowel".
vowel = ["A" , "E" , "I" , "O" , "U"]
def e_silaba(word):
if word[0] in vogal or word[1] in vowel:
return True
elif word not in vowel:
return False
else:
print "e_word:invalid argument"

If you want to verify that the word in question IS a word just by checking to see if it contains vowels, use this for loop:
for letter in word:
if letter.upper() in vowel:
return True
return False
This will check every letter in your word (regardless of length) to see if it is in your list vowel. Also note that it checks letter.upper(), which converts the letter to its uppercase version to accurately compare it to your uppercase vowel list. If it reaches the end of the word without having returned True, it means it did not encounter any vowels and will then return false.

If you wish to check if word contains only alphabetic characters you can use the .isalpha() method on it. As far as your function is concerned maybe you can solve it using sets like below:
vowels = set('aeoiu')
def e_silaba(word):
if (set(word.lower()).issubset(vowels)):
return True
else:
return False
What it does is first lowercase all the letters in word with the .lower() method, makes a set out of all characters in the new lower-cased word and checks if those characters are subset of the vowels set with the .issubset() method.
You also perhaps don't even need to make this function and explicitly return True or False. You can simply use set(word.lower()).issubset(vowels) which itself is a boolean expression that will return True or False.

Just to put #Chris_Rands's excellent comment into an answer: The simplest way is to turn the list of vowels into a set and compare the letters in word.lower() against it using any():
vowels = set("aeiou")
def e_silaba(word):
return any(x in vowels for x in word.lower())
If you want to make sure the word is not entirely composed of vowels you can use this solution:
vowels = set("aeiou")
def e_silaba(word):
if all(x in vowels for x in word.lower()):
return False
else:
return any(x in vowels for x in word.lower())
This will exclude "a" and "i" which actually are words though. As one last example, if you only want to check that condition for words of at least two characters, use this:
vowels = set("aeiou")
def e_silaba(word):
if len(word) > 1 and all(x in vowels for x in word.lower()):
return False
else:
return any(x in vowels for x in word.lower())
Hopefully this is enough to illustrate how you could add more conditions.

Try this
vowel=['A','E','I','O','U']
def e_silaba(word):
word=word.upper()
for i in vowel:
try:
word.index(i)
return True
except ValueError:
continue
return False
Output will be
>>> e_silaba('sandeep')
True
>>> e_silaba('dp')
False
>>> e_silaba('lda')
True
>>> e_silaba('bcf')
False
>>>

Related

How to check if in a string of words all the words start with the same letter

With a list like: 'apple,and,as'
All the words start with the same letter. If this is the case, I would like to return true and if not return false.
How can I do that?
A is just the example!! I need to check if the words begin in every random same letter
I'm a Beginner.
You can split the string into a list, then use a list comprehension to check if each word starts with 'a'. Then use the all function on the resulting list to see if they're all True.
words = 'apple,and,as'
print(all([word.startswith('a') for word in words.split(',')]))
Simply add the first letter of each word in a set. If the size of the set is 1 return True else False.
Hope this helps. :)
words = ['apple', 'and', 'as', 'apricot']
def function():
firstLetters = set()
for word in words:
firstLetters.add(word[0])
return len(firstLetters) == 1
result = function()
print("True") if result == True else print("False")

Python code - return first word in a string with vowel

Very new to Python.I would like to return the first work from an input string that starts with a vowel. If found return the word, else return an empty string. Have the below code however the else statement doesn't seems to work.
for word in string_list:
if word[0] in ['a','e','i','o','u']:
return word
else:
return ""
You only return inside a function, for example:
string_list = ['frst', 'hello', 'and']
def first_with_vowel(words):
vowels = 'aeiou'
for word in words:
if any(vowel == word[0] for vowel in vowels):
return word
return ""
print(first_with_vowel(string_list))
Output
and
To verify if any of the vowels is the first letter of a word you could use any. The function any evals to True if any of vowels is the first letter of the word.
Also in your code the else is misplaced, if the first word does not start with a vowel you will return "", even if the second does. You can remove the else, and return "" when the loop is over (like in the example code above), meaning there was no word that started with a vowel.
In your code, the for loop will execute only once if you are using it inside the function because you are just checking the first word and returning from the function. Instead, you can use only if condition inside the for loop and returning empty string part outside the for loop.
And you also need to check with small and capital letters/vowels. string_list here is the list of strings.
def findFirstWordWithVowel(string_list):
for word in string_list:
if word[0] in "aeiouAEIOU":
return word
return ""
return should be used in a function. so,
def checker(word):
if word[0] in ['a','e','i','o','u']:
return word
else:
return ""
checker("isuru")
this works.

how to Shorten this code or how to correct this code

Could you help me by shortening this code? I hope this is possible because I see it too redundant but I don't know how to avoid the repetition. I tried by creating two lists with even letters and odd letters (so basically by creating a new code), but then I don't know how to go on. This is the code:
Basically this is a function that has to check whether the input string has alternated vowels and consonants, like the word 'laser'.It has to return true if the string is alternating vowels and consonants, false in the other case(example: 'loss').
The other code I tried to create was this one:
The problem with the second code is that it returns me true for 'loss' and 'pair' (but they should be false) and 'laser' and 'p' true (as it should be)
and 'play' false (as it should be). How can i correct my error in the second code?
While iterating through each letter, just check two things:
The current letter IS a vowel and the next letter IS NOT.
The current letter IS NOT a vowel and the next letter IS.
You can do that like so:
def is_alternating(s):
s = s.lower()
vowels = 'aeiou'
for index, letter in enumerate(s[1:]):
if letter in vowels and (s[index] not in vowels) or letter not in vowels and (s[index] in vowels):
pass
else:
return False
return True
print(is_alternating("Laser"))
print(is_alternating("Loss"))
print(is_alternating("Pair"))
print(is_alternating("Racecar"))
# Prints:
# True
# False
# False
# True
This will also work by getting each letter at an even and odd index and using all():
def is_alternating(s):
s = s.lower()
vowels = "aeiou"
even = [s[i] for i in range(0, len(s), 2)]
odd = [s[i] for i in range(1, len(s), 2)]
return (
(all(letter in vowels for letter in even) and all(letter not in vowels for letter in odd)) or
(all(letter in vowels for letter in odd) and all(letter not in vowels for letter in even))
)
print(is_alternating("Laser"))
print(is_alternating("Loss"))
print(is_alternating("Pair"))
print(is_alternating("Racecar"))
The second solution is essentially saying:
even is every letter in s with an even index
odd is every letter in s with an odd index
The all() statement checks the following:
1.) Every even indexed letter IS in vowels and every odd indexed number is NOT
OR
2.) Every odd indexed letter IS in vowels and every even indexed letter IS NOT

How can I tell what value my function is returning in Python?

I'm trying to debug this program I wrote. How can I tell if, for a given word, hand, and word_list, it returns True or False? I tried initializing a variable failure and then modifying it and printing it's value. It isn't printing, so I don't know if it is behaving like it's supposed to. Any help is appreciated.
I have a function load_words() that returns a list of words. I know word is in word_list (I checked), so just trying to see if word is composed entirely of letters from the keys in the dictionary hand, which in this case it isn't, so it should return False.
Also, what is the difference between .keys() and .iterrkeys(), and is there a better way of looping through hand, perhaps with letter, value in hand.iteritems()?
word = 'axel'
hand2 = {'b':1, 'x':2, 'l':3, 'e':1}
def is_valid_word(word, hand, word_list):
"""
Returns True if word is in the word_list and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list.
word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
failure = False
if word in word_list:
print hand
print [list(i) for i in word.split('\n')][0]
for letter in [list(i) for i in word.split('\n')][0]:
print letter
if letter in hand.keys():
print letter
return True
failure = True
print failure
else:
return False
failure = False
print failure
else:
return False
failure = False
print failure
is_valid_word(word,hand2,load_words())
UPDATE I wish to use this function in my function, but it gives a key error, even though it works fine on its own.
def update_hand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
for letter in [list(i) for i in word.split('\n')][0]:
if letter in hand.keys():
hand[letter] = hand[letter]-1
if hand[letter] <= 0:
del hand[letter]
display_hand(hand)
return hand
The reason why it is not printing out is because you are returning the function before it prints. This means that the program stops before it reaches the print statement. For example:
def foo(x):
return x
print x
foo("asdf")
Will return nothing while:
def foo(x):
print x
return x
foo("asdf")
Will print:
asdf
So, all your statements before return. If not, it will not execute.
For your second clarification, this post already has your answer https://stackoverflow.com/a/3617008:
In Python 2, iter(d.keys()) and d.iterkeys() are not quite equivalent, although they will behave the same. In the first, keys() will return a copy of the dictionary's list of keys and iter will then return an iterator object over this list, with the second a copy of the full list of keys is never built.
Note that Python 3 does not have .iterkeys() too. Python 3 uses the previous .iterkeys() as the new .keys().
Lastly, I will review what is generally wrong with your code and what you want to achieve in descending order of severity.
Your code only checks one letter
[list(i) for i in word.split('\n')][0] is not how you get all the letters from a word.
You should make short code return first so that you would not have big indent blocks.
Your code only checks one letter
In your for loop, you return True immediately after the first word is checked. You should return True after the loop is completed instead.
for letter in word:
if letter not in hand.keys():
return False
return True
List comprehension
Your list comprehension is not needed (I'll tell you why later) and need not be so complex just to get the letters from a word. E.g.
[list(i) for i in word.split('\n')][0]
Actually only does this:
list(word)
In fact, you should just iterate through the word directly (as I did above), it will return the letters one by one:
for letter in word:
# code...
Make short code return first
Usually I dislike big chunks of highly indented code. What you can do is make the short code return first. For example:
if word in word_list:
for letter in word:
if letter in hand.keys():
return True
else:
return False
else:
return False
Can be simply be written as:
if word not in word_list:
return False
for letter in word:
if letter in hand.keys():
return True
else:
return False
However, this is just my opinion. Some others may prefer the else statement so that they know when the code is executed.
Your final code would look like:
def is_valid_word(word, hand, word_list):
if word not in word_list:
return False
for letter in word:
if letter not in hand.keys():
return False
return True
Clean right? However, I assume that you are making something like a scrabble game, so you would count if the words in your hand can for the word you chose. What you can add is something to count if the number of letters in the word is less than or equal to the number of letters in your hand:
def is_valid_word(word, hand, word_list):
if word not in word_list:
return False
# This makes the word into a "unique list"
letters = set(word)
for letter in letters:
if hand[letter] < word.count(letter):
return False
return True
EDIT
There was a problem with the code. It does not check if the letter is in hand in the if statement: if hand[letter] < word.count(letter):.
def is_valid_word(word, hand, word_list):
if word not in word_list and word not in hand.keys():
return False
letters = set(word)
for letter in letters:
# Add this extra clause
if letter in hand.keys() or hand[letter] < word.count(letter):
return False
return True
You can print the result directly print is_valid_word(word,hand2,load_words())
You have some indentation issues, and doing something after a return statement is futile.
You don't need to use keys or iterkeys the in operator will check for you, and will work with lists, set, dicts (keys), tuples, strings, ...
The in operator invokes __contains__ which is supported by most python collections.
Also have look at https://docs.python.org/2/reference/expressions.html#membership-test-details.
He is a minimized example of what you want to do with 3 tests.
def is_valid_word(word, hand, word_list):
"""
Returns True if word is in the word_list and is entirely composed
of letters in the hand. Otherwise, returns False. Does not mutate
hand or word_list.
word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
if word not in word_list:
return False
for letter in word:
if letter not in hand:
return False
return True
print(is_valid_word('bxel',
{'b': 1, 'x': 2, 'l': 3, 'e': 1},
['foo', 'bar', 'bxel']))
print(is_valid_word('axel',
{'b': 1, 'x': 2, 'l': 3, 'e': 1},
['foo', 'bar', 'axel']))
print(is_valid_word('axel',
{'a': 1, 'x': 2, 'l': 3, 'e': 1},
['foo', 'bar', 'axel']))

Check python function determine isogram from codewars

An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
Here is my code:
def is_isogram(string):
string = string.lower()
for char in string:
if string.count(char) > 1:
return False
else:
return True
And when I tried to run the test code Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" ) It failed, but I thought I did convert everything into lowercase. Can someone help?
Try this:
def is_isogram(string):
string = string.lower()
for char in string:
if string.count(char) > 1:
return False
return True
In your code when is_isogram("moose") is called, it will see that the first character's ('m') count is not greater than 1. So it will return True. Once it hits the return statement, it will stop the execution for the rest string. So you should really write return True only after for-loop to make sure that the function checks for the whole string.
If however, at any point, it finds a character's count to be greater than 1, then it will simply return False and stop executing because there's no point of checking any more when one point is found where condition does not hold.
How about using sets? Casting the string into a set will drop the duplicate characters, causing isograms to return as True, as the length of the set won't differ from the length of the original string:
def is_isogram(s):
s = s.lower()
return len(set(s)) == len(s)
print is_isogram("Dermatoglyphics")
print is_isogram("aba")
print is_isogram("moOse")
print is_isogram("")
This outputs:
True
False
False
True
Try this :
def is_isogram(s):
string = s.lower()
if len(s) == len(set(string)):
return True
return False
Try this out:
def is_isogram(string):
return len(string) == len(set(string.lower()))
"Implement a function that determines whether a string that contains only letters is an isogram."
By using sets, you can create unique elements. So if there are any repeating numbers, it will only select one. By calling len() on these strings, you can compare the length to the original.
Sorry if I explained it poorly. I am working on this.
let us define an isogram well:
according to wikipedia An Isogram is a word in which no letter occurs more than once.
check here for more about an isogram
just remind letter
I write this code and it works for me :
def is_isogram(argument):
print(len(argument))
if isinstance(argument,str):
valeur=argument.lower()
if not argument:
return False
else:
for char in valeur:
if valeur.count(char)>1 or not char.isalpha():
return False
return True
else:
raise TypeError("need a string ")
NB: the hidden test is the fact that you must check if the char in the string is a alpha character a-z, when i add this it pass all the hiddens tests
up vote if this help
I reckon this might not be the best solution in terms of maximizing memory space and time. This answer is just for intuition purposes using a dictionary and two for loops:
def is_isogram(string):
#your code here
#create an empty dictionary
m={}
#loop through the string and check for repeating characters
for char in string:
#make all characters lower case to ignore case variations
char = char.lower()
if char in m:
m[char] += 1
else:
m[char] = 1
#loop through dictionary and get value counts.
for j, v in m.items():
#if there is a letter/character with a count > 1 return False
if v > 1:
return False
#Notice the scope of the "return True" command. It is outside.
return True

Categories