Convert results in python to dictionary - python-2.7

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

Related

Counting vowels followed by consonants

I want to count the vowels in a text, this I can do. But I also want to count the amount of vowels followed by a consonant and the amount of vowels followed by a vowel. Can somebody help me with this?
This is what I have so far but it says invalid syntax for the line where I use i+1 in vowels.
s = "text"
vowels = set("aeuio")
consonants = set("qwrtypsdfghjklzxcvbnm")
vowelcount=0
vowelvowelcount=0
consonantcount=0
consvowelcount=0
consconscount=0
vowelconscount=0
for i in s:
if i in vowels:
vowelcount += 1
if i in consonants:
consonantcount +=1
for i in s:
if (i in vowels,and i+1 in vowels):
vowelvowelcount +=1
print ("number of vowels:", vowelcount)
print ("number of consonants:", consonantcount)
print ("number of vowels followed by vowels:", vowelvowelcount)
If you use for i in s, i is not an index: it is a character. A quick way to solve this is using:
for i in range(len(s)-1):
if s[i] in vowels and s[i+1] in consonants:
vowelconscount += 1
elif s[i] in vowels and s[i+1] in vowels:
vowelvowelcount += 1
# ...
Here we use range(..) to iterate over all indices up to (but excluding) len(s)-1. For each of these indices i we check if the character in s at position i (that is s[i]) is vowels and the next character s[i+1] is a cononant.
I like Willem's answer. I have another option. I might want to use enumerate in this case.
for i, char in enumerate(s[:-1]):
if char in vowels and s[i+1] in vowels:
vowelvowelcount +=1

Function to count upper/lower case letters

Could you please help me with writing a function to count alphabetic characters. My current output for this code is like this:
It contains 5 alphabetic characters of which 4 ( 80.0 %) are 'h'
My output for this code should be like this:
It contains 5 alphabetic characters of which 5 ( 100.0 %) are 'h'. I would like to treat both upper/lowercase letters equally
def count(p):
lows = "abcdefghijklmnopqrstuvwxyz"
ups = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numberOfh = 0
totalChars = 0
for achar in p:
if achar in lows or achar in ups:
totalChars = totalChars + 1
if achar == 'h':
numberOfh = numberOfh + 1
percent_with_h = (numberOfh / totalChars) * 100
print("It contains", totalChars, "alphabetic characters of which", numberOfh, "(", percent_with_h, "%)", "are 'h'.")
p = "Hhhhh"
count(p)
print p.lower().count("h")
I think should do what you want
Just change if statement to
if achar == 'h' or achar == 'H':
If you want to count all 'h' and 'H'.
If you want to count the occurrence of any letter in your string, rather than just h you could use something like this, which returns a dictionary containing each letter as the key, and the percentage as the value:
def count_alphas(s):
s = s.lower()
alpha_set = set(s)
alpha_counts = {}
for x in alpha_set:
alpha_counts[x] = s.count(x) / float(len(s)) * 100
return alpha_counts
# an example use:
print(count_alphas('thisissomeexampletext'))

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'

Checking charcters in a string and outputing a Single message

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)

How to double a char in a string?

I am trying to write a function that takes two arguments, a string and a letter. The function should then double the number of letter in the string. For example:
double_letters("Happy", "p")
Happppy
what i have done so far;
def double_letter(strng, letter):
new_word = ""
for char in strng:
if char == letter:
pos = strng.index(char)
new_word = letter+strng[pos:]
But this is giving me the output: pppy
how can i change the function to get the output: Happppy?
Use string.replace
string = 'happy'
letter = 'p'
string = string.replace(letter, letter + letter)
print string
You could use join and iterate through the characters in your string:
def double_letters(word, letter):
return "".join(2*i if i == letter else i for i in word)