Checking charcters in a string and outputing a Single message - list

a_lst = ['chair','gum','food','pizza']
letter = 'x'
for word in a_lst:
if letter not in word:
print ('no',letter)
elif letter in word:
print ('yes',letter)
Output:
no x
no x
no x
no x
Is there a way i can iterate though each item in "a_lst", check if each item has letter 'x'. if no item has letter 'x' print 'no x' just Once. If a word contains letter 'x', print 'yes x' just Once.
I think my logic is flawed somewhere.
Any suggestions?
Thanks

You could do this:
letter = 'x'
result = [a for a in a_lst if letter in a]
if result:
print('yes', letter)
else:
print('no', letter)
Explanation:
result will be [] if none of the words in a_lst has the letter. When you do a if result on an empty list, it returns False, otherwise it returns True. The conditional statements check and print the output statement accordingly.
Another way to do it in python is to use the filter function:
if filter(lambda x: letter in x, a_lst):
print('yes', letter)
else:
print('no', letter)
Yet another way to do it is to use any:
if any(letter in word for word in a_list):
print('yes', letter)
else:
print('no', letter)
any(letter in word for word in a_list) returns True if any of the words have the letter.

You can use the any function!
if any(letter in word for word in a_lst):
print('yes', letter)
else:
print('no', letter)

Have you tried something like this:
a = ['chair', 'gum', 'food', 'pizza']
letter = 'a'
result = 'no ' + letter
k = 0
for i in a:
if letter in a[k]:
print(a[k])
result = 'yes ' + letter
k += 1
print(result)

Related

letter changer lowercase to uppercase(vice versa) : Whats wrong in my code?

I wanted to enter a word with upperandlower letter combination letters and then when i press enter it will change vice versa
def changer(word):
for letter in word:
if letter.isupper():
letter.lower()
elif letter.islower():
letter.upper()
print word
word = raw_input()
changer(word)
You must append the converted letters to new string, and returning the new string could be helpful, too.
def changer(word):
newWord = ""
for letter in word:
if letter.isupper():
newWord += letter.lower()
elif letter.islower():
newWord += letter.upper()
print newWord
return newWord
...you do not return anything. and strings in python are immutable; you can not change them in-place.
this is something you could try:
def swapcase(word):
return ''.join(c.lower() if c.isupper() else c.upper() for c in word)
print(swapcase(word='Hello')) # hELLO
where i use str.join to join the generator that iterates over the characters with the swapped case.
speed-wise str.translate may be the better choice:
from string import ascii_lowercase, ascii_uppercase
trans_table = str.maketrans(ascii_lowercase + ascii_uppercase,
ascii_uppercase + ascii_lowercase)
def swapcase(word):
return word.translate(trans_table)
print('Hello'.translate(trans_table)) # hELLO

Convert results in python to dictionary

help to convert a python code results, where its finding the number of time the vowel appears in a string to dictionary?
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
if char in vowels:
count += 1
print ('Number of vowels: ' + str(count))
The result should be:
for apple: {'a' : 1, 'e' : 1}
A simple change like this would do: instead of incrementing count += 1, increment directly on a dictionary:
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
vowels_dict = {}
for char in s:
if char in vowels:
if char in vowels_dict:
vowels_dict[char] +=1
else:
vowels_dict[char] = 1
print (vowels_dict)
First, let's make vowels into a dictionary . We will need a second one to hold on to the matches we make in the first loop:
s = "apples"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
We will need to modify your for loop slightly to increment the value of the corresponding key (the vowels):
for char in s:
if char in vowels:
vowels[char] += 1
The for loop above checks if char is a vowel (or put simply, is one of the keys found in vowels). If it is, we increment the corresponding key's value by 1. For example, if char was "a", the if statement would return True and the key ("a")'s value (the integer after the colon) will increase by one. Now all we need is to put all the keys whose value is over 0 into the matches dictionary:
for vowel in vowels:
if vowels[vowel] < 1: # The vowel didn't appear in the word
continue
else:
matches[str(vowel)] = vowels[vowel]
The last line creates a new key for the matches dictionary (the matches[str(vowel)] part) then assigns the value of the new key equal to the value of the respective key in the vowels dictionary (the = vowels[vowel] part). Now all we need to do is to print out the matches dictionary:
print matches
Full code:
count = 0
s = "apple"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
for char in s:
if char in vowels:
vowels[char] += 1
for vowel in vowels:
if vowels[vowel] < 1:
continue
else:
matches[str(vowel)] = vowels[vowel]
print matches

How to get a letter from an element in a list

So I have some homework where it says that I have a list and if there is a vowel in the beginning and the last letter in each element of a list, I have to get those vowels in a string. So for example:
["Roberto", "Jessie", "A", "Geoffrey", "Eli"]
turns into
oeaei
So far I have this code:
vowels = "aeiou"
new_list = []
for words in a_list:
a_list = [words.lower() for words in a_list]
for letters in vowels:
if a_list[0] == vowels or a_list[-1] == vowels:
new_list += a_list[vowels]
return new_list
But I get the error
[]
[]
Traceback (most recent call last):
File "C:\Users\Miraj\Desktop\Q3.py", line 27, in <module>
test_get_first_last_vowels()
File "C:\Users\Miraj\Desktop\Q3.py", line 24, in test_get_first_last_vowels
print(get_first_last_vowels([]))
File "C:\Users\Miraj\Desktop\Q3.py", line 17, in get_first_last_vowels
if a_list[0] == vowels or a_list[-1] == vowels:
IndexError: list index out of range
So can I get some help where I'm going wrong. Thank you.
Okay
a_list = ["Roberto", "Jessie", "A", "Geoffrey", "Eli"]
You could try this:
a_list = ["Roberto", "Jessie", "A", "Geoffrey", "Eli"]
def start_end_vowels(a_list):
vowels = "aeiou"
result = ""
for words in a_list:
words = words.lower()
for vowel in vowels:
if len(words) == 1:
if words == vowel:
result += vowel
else:
if words.startswith(vowel):
result += vowel
if words.endswith(vowel):
result += vowel
return result
# Output
>>> a_list = ["Roberto", "Jessie", "A", "Geoffrey", "Eli"]
>>> start_end_vowels(a_list)
'oeaei'
>>> a_list = ["Abba"]
>>> start_end_vowels(a_list)
'aa'
This does work for your example, but I would double check with other test cases to be sure. It's good to know how to do this sort of question different ways.
Update: edited it to work for cases where starting vowel and ending vowel are the same.
You are working on an empty list. Further, this will never work:
>>> new_list += a_list[vowels]
TypeError: list indices must be integers, not str
Since vowels is a string, not an integer. You want to use append().
You are also checking the wrong condition:
if a_list[0] == vowels or a_list[-1] == vowels:
Should be:
if a_list[0] == letters or a_list[-1] == letters:
This needs to be executed for every word in a_list, so make sure it is inside the loop and not stand-alone.
This works:
def find_vowels(a_list):
vowels = set('aeiou')
res = []
for word in a_list:
if not word:
continue
word = word.lower()
if word[0] in vowels:
res.append(word[0])
if len(word) > 1 and word[-1] in vowels:
res.append(word[-1])
return ''.join(res)
Now:
>>> a_list = ["Roberto", "Jessie", "A", "Geoffrey", "Eli"]
>>> find_vowels(a_list)
'oeaei'
Your code has several flaws in the light of what you are trying to do , like you need not write
for words in a_list:
when you have written
a_list = [words.lower() for words in a_list]
the looping over all words is done by the second line alone.
Also when you say
if a_list[0] == vowels or a_list[-1] == vowels:
then a_list[0] or a_list[-1] is matched with the whole string 'aeiou', which will never be true. You need to match a_list[0] or a_list[-1] with individual vowels.
And lastly as #Idos said,
new_list += a_list[vowels]
this line is not going to work.
So I have written a fresh code taking all these into account and also considering the special case, if the word is a singe letter one. The code is given below
a_list = ["Roberto", "Jessie", "A", "Geoffrey", "Eli"]
vowels = ['a','e','i','o','u']
new_list = []
for word in a_list:
if len(word)>=2:
if word[0].lower() in vowels:
new_list.append(word[0].lower())
if word[-1].lower() in vowels:
new_list.append(word[-1].lower())
elif len(word)==1:
if word.lower() in vowels:
new_list.append(word.lower())
print (''.join(new_list))
You can employ listcomps or genexps to write a succinct program as follows. It has 3 lines and reads like English.
vowels = 'aeiou'
# collect
groups = (word if len(word) == 1 else (word[0], word[-1]) for word in words)
# flatten and filter
chars = (char for group in groups for char in group if char.lower() in vowels)
# consume the iterator
''.join(chars) # 'oeAEi'

Python: The code disobeys the conditional depending on the input

I'm making a hang man game. When I made the code with out a conditional and classes, it worked fine. Basically my issues with the code below are:
Only the letter "t" will match. I can't get any other letter to match.
If I enter "t" on the first try, then purposely get the next 4 letters wrong, it won't end until after 7 turns. Yet if I enter any other letter first, it will end after 4 wrong turns, like it should.
My questions....
How can I get it to match with the other letters that are in the self.word index?
Why is it not obeying the condition I set with the while loop in the main method if I enter "t" on my first try and get every other letter wrong thereafter?
class Hang():
def __init__(self):
self.turns = 0
self.word = ['t', 'h', 'i', 's']
self.empty = ["__", "__", "__", "__"]
self.wrong = []
def main(self):
while self.turns < 4:
for i in self.word:
choice = raw_input("Enter a letter a-z: ")
if choice == i:
index = self.word.index(i)
self.empty.pop(index)
self.empty.insert(index, i)
print self.empty
else:
print "Wrong"
self.wrong.append(choice)
print self.wrong
print self.empty
self.turns += 1
char1 = Hang()
char1.main()
In the game of hangman you can guess any character in the phrase in any order. But you're using a for loop to go through each character in order and it is only correct if the player correctly guesses the characters in order
Try this instead
while self.turns < 4:
choice = raw_input("Enter a letter a-z: ")
# optional, if user enters more than a single letter
if len(choice) > 1:
print "invalid choice"
continue # loop again from start
index = self.word.index(choice)
if index != -1:
# -1 indicates character in not int the string
# so this block is only executed if character is
# in the string
self.empty[index] = choice # no need to pop, you can simply change the value of the list at a given index
else:
print "wrong"
self.turns += 1
print self.empty

Hangman - duplicate char

I have one question regarding this hangman program of mine.When I guess the a letter('o') right of a word("good") which has duplicates,it's being unveiled only for the first index as list.index(value) returns only one index even if there are duplicates of that value.What do I need to change or add if I want to unveil all the duplicate letters at the same time.
Here's what I Expect the program to do:
Guess the letter: l >>> _oo_
Thanks.
the_word="good"
#print the_word
wLen=len(the_word)
u='_'*wLen
counter=0
while counter!=12 and wLen!=0:
counter=counter+1
print u
g=raw_input("Guess the letter: ")
p=list(the_word)
x1=the_word.find(g)
if x1 >=0:
u1=list(u)
u1[x1]=g
u=''.join(u1)
wLen=wLen-1
if wLen==0:
print "Congratulation!!!you have guessed the word"
print "The word was",the_word
else:
print "sorry u loose"
In case this is for an assignment, I'll focus on a simpler solution that will hopefully make sense. You know your target word, and from that you can use a function called enumerate to find the index positions of all of the letters:
In [31]: word = 'good'
In [32]: for index, letter in enumerate(word):
....: print index, letter
....:
0 g
1 o
2 o
3 d
So knowing this, let's say a user inputs o. Our current 'guessing' string looks like ____, and we know that we need to replace index positions 1 and 2 with o. Since the guess string and the target word have the same length (since they are supposed to be the same word), one simple solution would be to iterate over the actual word with enumerate, and if the letter is o (or whatever they guessed), replace the same index position in the guessing word with that letter. For example:
In [33]: word = 'good'
In [34]: guess_list = list('_' * len(word))
In [35]: g = raw_input('Guess a letter: ')
Guess a letter: o
In [36]: for index, letter in enumerate(word):
....: if letter == g:
....: guess_list[index] = letter
....:
In [37]: print ''.join(guess_list)
_oo_
while (true):
x1=the_word.find(g)
if x1 < 0:
break
u1=list(u)
u1[x1]=g
u=''.join(u1)
wLen=wLen-1
Something like this should work. Haven't tested it, but that should be the correct logic.