Write a value returning method, is vowel that returns true if a given characters is vowel otherwise returns false. Write a program that prompts the user to input a sequence of characters and outputs the number of vowels. Please help me to run this problem and what is the exact code
You can use char in "aeiouAEIOU" to determine if a character is a vowel, and use a list comprehension to produce a list containing only vowels, and find the number of vowels in the input string by finding the length of this list.
string=raw_input()
numOfVowels=len([char for char in string if char in "aeiouAEIOU"])
print(numOfVowels)
Input:
abcdefghijklmnopqrstuvwxyz
Output:
5
make a list of vowel letter to comapre letters in input that user enters:
vowel = ['a', 'e', 'i', 'o', 'u']
user_ask = input("enter a string to count the vowel:\t").casefold()
by using casefold method, you do not need to worry about upper and lowercase letters.
count = 0
new_vowel = []
for i in user_ask:
if i in vowel:
count += 1
new_vowel.append(i)
print("number of vowels\n", count)
you can use counter if you want to print them in a key value pairs, i.e. as a dictionary.
from collections import Counter
dict(Counter(new_vowel))
Output
enter a string to count the vowel: I am trying to learn
number of vowels :
6
and the dictionary form is:
{'i': 2, 'a': 2, 'o': 1, 'e': 1}
Related
As my first personal project I am building a Wordle "solver" that comes up with a first guess word then takes an input of the letters that were correct in the word then searches the word list for words with similar characters. To do this I stored each word in a dictionary with the key being the word and the value being each character in the word i.e dodge: [d, o, d, g, e]. I am currently experimenting to get code running that parses through the values of the dictionary to match the characters to the inputted letters but am stumped on how to search through the lists within the dictionary as a loop.
Here's my code for inputting the correct letters:
correct_letters_1 = list(letters for letters in input("Input corrects letters: ").strip().split())
Here's one of my attempts at parsing the dictionary:
for letters in correct_letters_1:
if letters in word_dictionary.values():
print("yes")
I'm pretty sure this problem has something to do with my code parsing the entire lists within the dictionary rather than each individual character but even when I try inputting the whole word, i.e Input Correct Letters: d o d g e; I still don't have any output.
If someone could put a beginner on the right track it would be much appreciated.
You might be looking to compare the whole list, rather than the letters:
correct_letters_1 = list(input("Enter correct letters: ").strip())
# correct_letters_1 is a whole list
if correct_letters_1 in word_dictionary.values():
print("yes")
# Inputting "abc"
>>> correct_letters_1
['a', 'b', 'c']
>>> word_dictionary
{'abc': ['a', 'b', 'c']}
>>> correct_letters_1 in word_dictionary.values()
True
To check if the user's guess is a subset of any of the words:
correct_letters_1 = list(input("Enter correct letters: ").strip())
let_set = set(correct_letters_1)
word_dictionary = {'abc': ['a', 'b', 'c'],
'abcde': ['a', 'b', 'c', 'd', 'e'],
'ab': ['a', 'b'],
'test': ['t', 'e', 's', 't']}
# Check to see if correct_letters_1 is a subset of any word in the dictionary
close_words = ["".join(x) for x in word_dictionary.values() if let_set <= set(x)]
Which can be simplified to:
correct_letters_1 = input("Enter correct letters: ").strip()
let_set = set(correct_letters_1)
words = ["abc", "test", "ab"]
# Check to see if correct_letters_1 is a subset of any word in the list words
close_words = [x for x in words if let_set <= set(x)]
I'm trying to reverse a string, so I converted the string into a list and was trying to send the last element to the front, 2nd to last element to the 2nd space, etc.
word = input("Enter a word: ")
word = list(word)
count = 0
while count < len(word):
word.insert(count, word.pop())
count = count + 1
print(word)
It just returns the original string in list form, even though I'm saving the last letter and inserting it before popping it off of the string? Does word.pop() not capture the last letter of a string before deleting it or am I overlooking something?
Well the simplest way to do what you are trying is to slice the string in reverse order, this does not even require changing into a list:
word = input("Enter a word: ")
return word[::-1]
Here's an experiment:
>>> word = list('python')
>>> word.insert(0, word[-1])
>>> word
['n', 'p', 'y', 't', 'h', 'o', 'n']
>>> word.remove(word[-1])
>>> word
['p', 'y', 't', 'h', 'o', 'n']
Wait, what?!
>>> help(word.remove)
Help on built-in function remove:
remove(value, /) method of builtins.list instance
Remove first occurrence of value.
Raises ValueError if the value is not present.
Remove first occurrence of value.
So, you inserted word[-1] at the beginning of the list, and then word.remove immediately removes the first occurrence of word[-1], which is now at the beginning of the list, you've just inserted it there!
You're setting the variables inside the while-loop to the same value. Also, use list.pop to remove the element from the list. For example:
word = input("Enter a word: ")
word = list(word)
count = 0
while count < len(word):
word.insert(count, word.pop())
count = count + 1
print(word)
Prints:
Enter a word: book
['k', 'o', 'o', 'b']
Here is the docstring for list.remove:
>>> help(list.remove)
Help on method_descriptor:
remove(self, value, /)
Remove first occurrence of value.
Raises ValueError if the value is not present.
>>>
As you can see, list.remove removes the first occurrence of the given value from the list. All your backwards function does right now is take the last character of the word, add it to the front and then immediately remove it from the front again. You do this once for every character in the word, the net result being no change.
I want to sort a dictionary alphabetically but we have other letters in Turkish because of that i can't use sorted() function.
For example we have letter "ç" which comes after letter "c". How can i make letter "ç" comes after letter "c"?
Btw it will not be just 1 letter we have plenty more and dictionary will contain hundereds of words and values.
Here is a simple solution based on the Turkish alphabet:
alphabet = "abcçdefgğhıijklmnoöprsştuüvyz"
words = ["merhaba", "aşk", "köpek", "Teşekkürle"]
sorted_words = sorted(words, key=lambda word: tuple(alphabet.index(c) for c in word.lower()))
This code is able to sort words using the lexicographic order. It also works with words containing capital letters.
You can use key argument for sorted, however the main challenge is how to define which letter is "bigger". Maybe you can use some table of letters' values to sort them. Like this:
LETTER_VALUES = {
...
"c": 100,
"ç": 110
...
}
sorted_ar = sorted(char_array, key=lambda ch: LETTER_VALUES.get(ch1, ord(ch)))
Of course, numbers are just random for example and ord the simplest example for "failure default".
You can achieve this by injecting your own alphabet order, example:
letters = "abcçdefgğhıijklmnoöprsştuüvyz"
letters_dict = {i:letters.index(i) for i in letters}
print(sorted("açobzöğge", key=letters_dict.get))
The above should output:
['a', 'b', 'ç', 'e', 'g', 'ğ', 'o', 'ö', 'z']
The program identifies if one of the elements in the string word is a consonant by looping though the word string, and then for each iteration though the word string, iterating though the consonants list and comparing if the current element in word string equals to the current element of consonant list.
If yes, the current element of the word string is a consonant and the consonant gets printed (not the index of the consonant, but the actual consonant, for e.g. "d".)
The problem is, I get this instead:
1
1
What am I doing wrong? Shouldn't the nested loops work so that the below loop iterates every element for each element in the above loop? That is, each index above makes the below loop iterate though each index?
That's the program:
word = "Hello"
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
for character in range(len(word)):
for char in range(len(consonants)):
if consonants[char] == word[character]:
consonant = word[character]
print consonant
You are misreading the output. The character is the letter L lowercase, not the number 1.
In other words, your code is working as designed. The captital letter H is not in your consonants list, but the two lowercase letters l in Hello are.
Note that it'd be much more efficient to use a set for consonants here; you'd not have to loop over that whole list and just use in to test for membership. That works with lists too, but is much more efficient with a set. If you lowercase the word value you'd also be able to match the H.
Last but not least, you can loop over the word string directly rather than use range(len(word)) then use the generated index:
word = "Hello"
consonants = set('bcdfghjklmnpqrstvwxz')
for character in word.lower():
if character in consonants:
print character
Demo:
>>> word = "Hello"
>>> consonants = set('bcdfghjklmnpqrstvwxz')
>>> for character in word.lower():
... if character in consonants:
... print character
...
h
l
l
I'm trying to see if a word or sentence has each letter of the alphabet and I can't get it to print all the letters that isn't in the sentence/word.
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z']
x = raw_input('')
counter = 0
counter2 = 0
for i in range(len(x))
counter += 1
for o in range(26):
counter2 += 1
if alpha[counter2] not in x[counter]:
and I'm stuck there...
alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z'}
input_chars = set(raw_input())
print alphabet - input_chars
All we do is set difference between the set of alphabet characters and the set of characters in our input. Note that the difference operation can take as a second operand any iterable, so we don't even really have to turn our input into a set if we don't want to, although this will speed up the difference a small amount. Furthermore, there is a built-in string which gives us the ascii letters so we could do it like this:
import string
print set(string.ascii_lowercase) - raw_input()
using set difference:
import string
x=raw_input()
not_found=set(string.ascii_lowercase) - set("".join(x.split()))
print (list(not_found))
output:
>>>
the quick brown fox
['a', 'd', 'g', 'j', 'm', 'l', 'p', 's', 'v', 'y', 'z']
Since you're already iterating over both strings, there is no need to use counter and counter2.
You were almost there. Python makes list operations simple, so there's no need to iterate over the lists element-by-element using indices:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
sentence = raw_input('Enter a sentence: ').lower() # Because 'a' != 'A'
letters = []
for letter in sentence:
if letter in alphabet and letter not in letters:
letters.append(letter)
print(letters)
Much easier:
import string
x = raw_input()
print [c for c in string.ascii_lowercase if c not in x]