How to write code where you don't define a variable - python

I am trying to solve this problem below
Assume s is a string of lower case characters. Write a program that
counts up the number of vowels contained in the string s. Valid vowels
are: 'a', 'e', 'i', 'o', and 'u'. For example, if s =
'azcbobobegghakl', your program should print:
Number of vowels: 5
I wrote the following code
s='azcbobobegghakl'
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
This was not correct. I learned that you should not define "azcbobobegghakl" as s or g or anything else for that matter. Do I need to use a certain function to accomplish this?

You can use a list comprehension and then count the list.
print("Number of vowels: {}".format(len([vowel for vowel in input() if vowel in "aeiou"])))
The question is asking to count the number of vowels in any string, not just the example azcbobobegghakl, therefore you should replace the fixed string with an input().

What you have seems to do the task required by the question, however, if the do want it in the form of a function you can restate the code you already have as a function:
def count_vowels(s):
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
Then, you can execute your program with the following:
count_vowels('azcbobobegghakl')

s = str(input("Enter a phrase: "))
count = 0
for vowel in s:
if vowel in 'aeiou':
count += 1
print("Number of vowels: " + str(count))
This seems to work on python but it is not the right answer.

Related

Printing the vowels and the vowel count in a string

I will have to define a function that takes a person's full name and finds the total number of vowels in that input. And I need to output every vowel including the total
number of vowels found. If the name does not contain any vowel then my function should print
“No vowels in the name!”. Two sample inputs and their corresponding outputs are given below:
Sample input:
(Steve Jobs)
(XYZ)
Sample Output:
Vowels: e, e, o. Total number of vowels: 3
No vowels in the name!
I know it is quite a simple program, but I am facing some difficulties in printing an output as shown in the Sample Output. Here's my incomplete code:
def vowels(full_name):
for i in full_name:
count = 0
if i == 'a' or i == 'A' or i == 'e' or i == 'E' or i == 'i' or i =='I' or i == 'o' or i == 'O' or i == 'u' or i == 'U':
count += 1
print(i, end= ',')
print('Total number of vowels: ', count)
How can I write a clean program to get the expected output? I'm really lost at this point
Some things that may be helpful: As the comments have already pointed out, your long chain of ors can be shortened by using in to check for substring membership:
>>> "a" in "AEIOUaeiou"
True
>>> "b" in "AEIOUaeiou"
False
>>>
You can use filter to create a collection of vowels - only retaining those characters which are vowels:
def is_vowel(char):
return char in "AEIOUaeiou"
vowels = list(filter(is_vowel, "Bill Gates"))
print(vowels)
Output:
['i', 'a', 'e']
>>>
You know that if vowels is empty, you can print "No vowels in the name!". If it's not empty, you can print your other message, and use str.join on vowels to print the vowels, seperated by commas:
print(", ".join(vowels))
Output:
i, a, e
>>>
The number of vowels found is just the length of vowels.
vowels = "aeiou"
def is_vowel(char):
return char in vowels
def count_vowels(word):
vowels = [char for char in word if is_vowel(char.lower())]
return len(vowels)
print('Total number of vowels:', count_vowels("Steve Jobs"))

How to check if one character is next to another (Flesch index)?

I'm learning to work with strings and my project is to calculate the number of syllables in a sentence.
I'm given some code that calculates the syllables by adding to the variable, syllables += 1, for each vowel. But the end product is wrong because consecutive vowels should only count as a single +1. For example the word "certain" should return two syllables, not three. There is more to it than this but it's not relevant to my question.
Here is how I solved the problem, with an explanation below:
syllables = 0
vowels = "aeiouAEIOU"
vowelContainer = "" # Part of my added code for solution. Create some container to hold
# a representation of consecutive vowels.
for word in text.split():
for vowel in vowels:
syllables += word.count(vowel)
for ending in ['es', 'ed', 'e']:
if word.endswith(ending):
syllables -= 1
if word.endswith('le'):
syllables += 1
for vowel in word: # My added code for solution: rest of lines that follow
if vowel == vowel in vowels: # I fill in the container with Ts and Fs to create a string
vowelContainer += "T" # that I can then check for consecutive vowels.
else:
vowelContainer += "F"
count2ConsecutiveVowels = vowelContainer.count("TT") # I count how many times there are two
count3ConsecutiveVowels = vowelContainer.count("TTT") # or three vowels in the word.
syllables = syllables - count2ConsecutiveVowels - count3ConsecutiveVowels # I subtract the count
vowelContainer = "" # from total syllables
# At the end of the loop I empty the container for the next word.
I managed to come up with a solution, but it is messy. Is there a simpler way to do this?
I think this code should work:
vowels = "aeiouAEIOU"
text = "certain"
syllables_count = 0
if len(text) == 1:
if text[0] in vowels:
syllables_count += 1
else:
for i in range(len(text) - 1):
if text[i] in vowels and text[i+1] not in vowels:
syllables_count += 1
elif text[i] in vowels and i+1 == len(text) - 1:
syllables_count += 1
print(syllables_count)
In order to solve the problem of consecutive vowels you mentioned above, and get the correct number of syllables, I suggest using a regular expression as in the following example:
import re # put in the beginning to import regular expression module
word='certaaaaiin' # just for example
a=re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',word)
syllables =len(a)
print(syllables)
# output is 2
In this method, any number of consecutive vowels is considered as one in counting
in the regular expression [aeiouAEIOU](?![aeiouAEIOU]), it selects any vowel in the list, in case of that vowel does not have another one after.
vowels = "aeiou"
count = 0
with open("/home/doofinschmurts/PycharmProjects/Practice_001/text.txt", "r") as text:
text = text.read()
for character in range(len(text) - 1):
if text[character] in vowels and text[(character + 1)] not in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character + 2] in vowels and text[character - 1] not in vowels:
count += 1
print(count)
I'm new to coding but this script works and the main "jist" is in the long if statements. This wont be the best answer; however, if any veterans wouldn't mind critiquing me also.
Every time you encounter a vowel, you need to increment the syllables counter by 1. Otherwise, you can ignore it.
Try this and see if this meets your needs.
text = input('Enter your word(s) :')
syllables = 0
vowels = "aeiou" #no need to check for upper and lower
for word in text.split():
vowel_found = False #initialize vowel_found to False and check if the world has vowels
for char in word: #iterate thru each char in the word
if not vowel_found and char.lower() in vowels: #for every new vowel found, increment syllables by 1
syllables +=1
vowel_found = True
else:
vowel_found = False #reset to increment counter again
print (syllables)
Here's the output I got:
Enter your word(s) :syllables
2
Enter your word(s) :certain
2
Enter your word(s) :book
1
Enter your word(s) :case
2
Enter your word(s) :Heart
1
Let me know if this code fails. I would like to improve this.

Removing ending vowels from a word

This function receives a string as input and should return the number of syllables in the string.
This function has following conditions:
1. Number of syllables is equal to the number of vowels
2. Two or more consecutive vowels count only as one.
3. One or more vowels at the end of the word are not counted.
This is what I've so far but clearly I'm still missing a lot. I'm not sure how to continue here, so I hope you guys can help.
def syllables(word):
vowels = ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
# I've no idea how to remove all ending vowels though
word = word[:-1]
# List with vowels that appear in the word
vowelsList = [x for x in vocals if x in word]
N = []
for i in word:
if i in vowels:
N += i
N = len(N)
return N
print(syllables("bureau"))
# Should print "1" but prints "3" instead
I suggest you the following simple code:
def syllables(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
N = 0
previousLetterIsAVowel = False
# Perform a loop on each letter of the word
for i in word.lower():
if i in vowels:
# Here it is a vowel
# Indicate for the next letter that it is preceded by a vowel
# (Don't count it now as a syllab, because it could belong to a group a vowels ending the word)
previousLetterIsAVowel = True
else:
# Here: it is not a vowel
if previousLetterIsAVowel:
# Here it is preceded by a vowel, so it ends a group a vowels, which is considered as a syllab
N += 1
# Indicate for the next letter that it is not preceded by a vowel
previousLetterIsAVowel = False
return N
print(syllables("bureau")) # it prints 1
print(syllables("papier")) # it prints 2
print(syllables("ordinateur")) # it prints 4
print(syllables("India")) # it prints 1
I also provide a one-line style solution using regex, easily readable too if you know a little bit about regex. It simply counts the number of groups of consecutive vowels that are followed by a consonant:
import re
def syllables(word):
return len(re.findall('[aeiouy]+[bcdfghjklmnpqrstvwxz]', word.lower()))
To check the last vowel you can try something like this (I wouldn't iterate as you're going to loose whole syllables): -> EX: Italian word "Aia" (threshing floor)
if word[-1] in vocals:
word=word[:-1]
-- sorry but I didn't manage to put 'code' into comments so a posted an answer
I would go for:
def syllables(word):
def isVowel(c):
return c.lower() in ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
while word and isVowel(word[-1]):
word = word[:-1]
lastWasVowel = False
counter = 0
for c in word:
isV = isVowel(c)
# skip multiple vowels after another
if lastWasVowel and isV:
continue
if isV:
# found one
counter += 1
lastWasVowel = True
else:
# reset vowel memory
lastWasVowel = False
return counter
Stolen from LaurentH:
print(syllables("bureau")) # prints 1
print(syllables("papier")) # prints 2
print(syllables("ordinateur")) # prints 4
print(syllables("I")) # prints 0
I think we have return 1 if there is previousLetterIsAVowel and N returns 0. Example word Bee.
In Addition to Laurent H. answer
if N == 0 and previousLetterIsAVowel:
return 1
else:
return N

Counting the number of vowels

Trying to print no. of vowels. When I run this code I get 1,2,3,4 I intend to print only 4. Where is my mistake and how would I correct it?
vowels='a','e','i','o','u'
s= 'hellohello'
count = 0
for letters in s:
if letters in vowels:
count+=1
print (count)
You're mostly right, but you're printing in the loop rather than at the end.
for letters in s:
if letters in vowels:
count+=1
# de indent to close the loop
print (count)
count should be out of for loop.So that it prints only once.
vowels='a','e','i','o','u'
s= 'hellohello'
count = 0
for letters in s:
if letters in vowels:
count+=1
print (count)

Pig Latin conversion of List of strings yields only first string, Python 3

I wonder if you can help me find an error in my code. I am reading a sentence from a text file to convert to Pig Latin and calling the result "string."
words = string.split()
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
for word in words:
position = 0
while word[position] not in vowels:
position += 1
if word[position] in vowels:
return word[position:] + word[:position] + "ay"
Could someone explain why this only converts the first word in the sentence? I thought the for loop would pass through all words in the sentence.
__
Edit 3/12/2016 at 2:46pm
Thanks very much for your help, everyone. I followed the approach closest to Saleem's, and I have the output coming out in one string, as I wish, due to having set an empty string called "answer."
The problem comes with the final word in the string of text I wish to convert, when the first character + "ay" is placed on a new line from the rest. Does anyone know why this happens?
words = string.split(" ")
answer = ""
for word in words:
if word[0] in vowels:
answer += word + "way" + " "
else:
position = 0
for char in word:
if char not in vowels:
position += 1
else:
break
answer += word[position:] + word[:position] + "ay" + " "
return answer
for the string "Last word comes out on a new line."
it yields something like this:
astLay ordway omescay outway onway away ewnay ine.
lay
The for loop would go through each word, but you cut it short with return ... If you go to a party and then return with one box of cookies, you need to go back in order to return with another. It is the same with a function: to return more than one value, you need to call the function more than one time. You could use yield instead and use list(myfunction(string)) when calling it, but you could also create a list to return at the end:
words = string.split()
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
answer = []
for word in words:
position = 0
while word[position] not in vowels:
position += 1
if word[position] in vowels:
answer.append(word[position:] + word[:position] + "ay")
return answer
You are returning out really. Can also shorten to
def is_vowel(char):
return char in ['a', 'e', 'i', 'o', 'u', 'y']
def piglatin(sentence):
words = sentence.split()
piglatin_words = []
for word in words:
index = [is_vowel(ch) for ch in word].index(True)
piglatin_words.append(word[index:] + word[:index] + 'ay')
return ' '.join(piglatin_words)
print piglatin('this is my original sentance')
You are calling return at end of your procedure which will simply exist loop with only first word. You can achieve your goal even without return. e.g. populate a list with desired result and return list at end.
Here is another way to return iterator using yield keyword. See code snippet below.
def process(string):
words = string.split()
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
for word in words:
position = 0
while word[position] not in vowels:
position += 1
if word[position] in vowels:
yield word[position:] + word[:position] + "ay"
# Usage example
data = "Be sure to leave a comment if you can help the user out"
result = process(data)
for w in result:
print(w)
Output:
eBay
uresay
otay
eavelay
aay
ommentcay
ifay
youay
ancay
elphay
ethay
useray
outay
One minor suggestion to using a generator - don't write a function for it, use a class and override __iter__.
Why is better explained here, but in short if you pass the function iterator to something that will also iterate the object, it gets a reference to the original iterator. This causes the iterator to be completely consumed before the first function iterates completely, and you'll get a traceback for StopIteration.
Overriding __iter__ allows us to get a new instance of the iterator, instead of a reference.
class Piglatin(object):
"""
Overrides the __iter__ protocol for yielding a piglatin version
of each word in a provided sentence.
By overriding the __iter__ magic method, this iterator becomes consumable
by multiple layers of function calls.
"""
def __init__(sentence):
self.sentence = sentence
self.vowels = set(['a', 'e', 'i', 'o', 'y'])
def __iter__(self):
for word in self.sentence:
position = 0
while word[position] not in vowels:
position += 1
if word[position] in vowels:
yield word[position:] + word[:position] + "ay"
I believe this is a way more efficient answer to the above question. this is my first answer on stack overflow and I am open to any kind of feedback.
def navy_code(txt) :
for word in txt.split():
first = word[0]
if first in 'aeiouAEIOU' :
crypt = word + 'ay'
else :
crypt = word[1:]+first+'ay'
yield crypt
result = navy_code("Place the submarine under an allied countrys command if possible")
for answer in result:
print(answer)
OUTPUT: lacePay hetay ubmarinesay underay anay allieday ountryscay ommandcay ifay ossiblepay

Categories

Resources