I'm trying to work on some Python code where a person is prompted to input a string of text. Then I need to find the position of all of the vowels in the string. I have this, but it's not working...
userInput = (input("Enter a line of text: ")
vowels = ("aeiouAEIOU")
position = 0
for char in userInput :
if char in vowels :
position = userInput.find(vowels)
print(char, position)
It returns the vowels but gives each position as -1. What am I doing wrong? I have read that the index function could be used, but we're not getting to that for a few more weeks. Any suggestions on simple fixes I could make to this code? Thank you!!
Your code has the mistake that when you do userInput.find(vowels) remember that the string vowels is "aeiouAEIOU" so it will not find that unless the either string "aeiouAEIOU" is in userInput. Instead, it is best to enumerate and return those indexes.
userInput = input("Enter a line of text: ")
vowels = "aeiouAEIOU"
for i, char in enumerate(userInput):
if char in vowels:
print(char, i)
You can do this with a list comprehension and enumerate:
positions = [i for i, char in enumerate(userInput) if char in vowels]
This will give you a list of the indices of vowels - it enumerates your user input string as a list of characters with an index, and applies a predicate- in this case if the character is a vowel or not.
Once the test char in vowels is verified, you are currently reading a letter char that is a vowel, at that point you can output it directly. On the other hand you need to remember the position by incrementing it every time you move to the next char:
userInput = "This is some input from the user"
vowels = "aeiouAEIOU"
position = 0
for char in userInput:
if char in vowels:
print(char, position)
position += 1
This code can be improved to be a bit more pythonic, using enumerate can save you from keeping track of the position by hand:
serInput = "This is some input from the user"
vowels = "aeiouAEIOU"
for position, char in enumerate(userInput):
if char in vowels :
print(char, position)
Another improvement can be made, this time we can improve performances. Time cost of checking char in vowels is proportional to the size of the string vowels. On the other hand you can change the type of vowels from string to set, checking if an item is part of a set is done in constant time:
userInput = "This is some input from the user"
vowels = set("aeiouAEIOU")
for pos, char in enumerate(userInput):
if char in vowels:
print(char, pos)
string find(str,str, beg=0, end=len(string))
method determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given. In your code,userInput.find(vowels) it would check the userInput if it contains the whole bunch of vowels which is "aeiouAEIOU". so the code can be improved as follow:
userInput = (input("Enter a line of text: ")
vowels = ("aeiouAEIOU")
position = 0
for char in userInput :
if char in vowels :
position = userInput.find(char)
print(char, position)
Try the below code, it's similar to yours:
userInput = input("Enter a line of text: ")
vowels = "aeiouAEIOU"
for count in userInput:
x = 9 #there are 10 vowels, from 0 to 9
while x >= 0:
if count == vowels[x]:
print("\n",count)
x -= 1
print("\n Done")
Related
I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter.
The code seems okay but I don't get the desired result.
words is a list of words I have written before the function.
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.
How should I replace the desired hash string with guess letter?
it replaces all the hashes
This is exactly what blank.replace is supposed to do, though.
What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:
for num in a:
blank[num] = guess
print(blank)
A couple things to note:
inefficient/un-pythonic pop operation (see this)
l_count is just len(word)
un-pythonic, unreadable replacement
Instead, here's a better implementation:
def word_guess() -> str:
random.shuffle(words)
word = words.pop()
guess = input()
out = ''
for char in word:
if char == guess:
out.append(char)
else:
out.append('-')
return out
If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:
word = 'hangman'
blank = '-------'
guess = 'a'
if guess in word:
blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
blank_reformed
'-a---a-'
(You still have some work to do make the overall game work...)
I am trying to solve an exercise regarding strings in Python. The exercise says: Write a function that takes a string word and returns a list of strings containing the sound elements of the given word.
A sound element is a maximal sequence of 1 or more consonants followed by 1 or more vowels. In other words, i am supposed to iterate over a string of characters and split it everytime a vowel is followed by a consonant.
Example:
the following string given in input:
S = 'unconditionally'
should return the following list
L = ['u','nco','ndi','tio','na','lly']
In order to solve the exercise, i have written the following function:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels:
string += S[i]
elif S[i] in vowels and S[i+1] not in vowels:
string += S[i]
syllables.append(string)
string = ''
return syllables
Which should be able to solve it. The problem is that i get an index-out-of-range error everytime i run the program. I know the issue is in the elif statement which i don't know how to get rid of.
Is there any way to solve this exercise without importing any external libraries?
Any help will be appreciated
You iterate till the index of the last character :
for i in range(len(S)):
and you have this line:
elif S[i] in vowels and S[i+1] not in vowels:
if i is the last index of S, then it will throw error on S[i+1]
Edit: You can use this:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels:
if len(string) == 0 or not string[-1] in vowels: #here I check if length of string is 0
#in this case I can append letter to it. And also if last letter (`string[-1]`) isn't a vowel,
#then also I can add this letter to string
string += S[i]
else: # if last letter was vowel then we reset string.
syllables.append(string)
string = ''
string += S[i]
else:
string += S[i]
syllables.append(string)
return syllables
We can further simplify code, because we have string += S[i] in every block of if-else:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels and len(string) > 0 and string[-1] in vowels:
syllables.append(string)
string = ''
string += S[i]
syllables.append(string)
return syllables
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.
This is my code so far, however it still prints words which begin with "g" and does not print the last word.
famous_quote = input("Enter a one sentence quote: ").lower()
word = ""
for ltr in famous_quote:
if ltr.isalpha() == True:
word = word + ltr
else:
if word > "g":
print(word)
word = ""
else:
word = ""
I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.
Sample input:
Wheresoever you go, go with all your heart
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Algorithm I've come up with:
- split the words by building a placeholder variable: word
- Loop each character in the input string
- check if character is a letter
- add a letter to word each loop until a non-alpha char is encountered
- if character is alpha
- add character to word
- non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
- else
- check if word is greater than "g" alphabetically
- print word
- set word = empty string
- or else
- set word = empty string and build the next word
- Hint: use .lower()
You can define a neat little generator to split your sentence into words and compare the first letter of each.
def filter_words(sentence, lo, hi):
lo, hi = map(str.upper, (lo, hi))
words = sentence.upper().split()
for word in words:
if lo <= word[0] <= hi:
yield word
sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')
WHERESOEVER
YOU
WITH
YOUR
HEART
This is how I approached this problem. It gave me a hard time since I am a beginer. But it seems to work fine.
quote = "quote goes here"
word = ""
for letter in quote:
if letter.isalpha():
word += letter
else:
if word > "":
print(word.upper())
word = ""
else:
word = ""
print(word.upper())
I added the space to the user_input and also used the word > 'h'. Below is how it looks:
user_input = input('Enter a phrase: ').lower()
user_input += ' '
word = ''
for char in user_input:
if char.isalpha():
word += char
else:
if word > 'h':
print(word.upper())
word = ''
else:
word = ''
This code worked for me...
The task is: Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z
I was making the mistake of using word > "g" before, which needs to be replaced by word > "h".
Also, you need to add the last print command in order to print the last word in case the phrase does not end with a punctuation (as in the given example)
phrase = input ("Please enter a phrase: ").lower()
word = ""
for letter in phrase:
if letter.isalpha():
word += letter
else:
if(word > "h" ):
print(word)
word = ""
else:
word = ""
if word.lower() > 'h':
print(word)
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.
The two issues you've highlighted is that you are comparing the whole word instead of just the first character.
Simply change:
if word > "g":
To:
if word and word[0] > "g":
And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:
if word:
print(word)
You may note the output is all uppercase, so .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:
famous_quote = input("Enter a one sentence quote: ")
...
if word and word[0].lower() > "g":
Note: You can simplify your else: condition:
else:
if word and word[0] > "g":
print(word)
word = ""
You stated that you are not allowed to use the split() method. I am not sure what you can use, so here's a solution (not the optimal one).
famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
if current_word is None:
current_word = c # start a new word
else:
current_word += c # append a new letter to current word
else:
if current_word is not None:
f = current_word[0] # first letter
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print(current_word)
current_word = None
Here is a sample run of the program. It preserves lowercase and uppercase. It also splits words on any non-ASCII character.
Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you
Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.
Assuming that the famous quote contains only spaces as word separator, this should do the job:
words = input("Enter a one sentence quote: ").lower().split()
for word in words:
if word[0] > 'g':
print("{w} ".format(w = word))
split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.
print() can be used in a lot of ways, due to python's history with this function.
You can .join() the list (getting a string as result) and print it:
print(" ".join(words))
you can also print with concatenations (considered ugly):
print(word+" ")
or you can use formatted printing, which I do use a lot for readibility:
print("{w} ".format(w = word))
interprets "{w}" and replaces it with word wherever "{w}" appears.
Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).
1. Split the words by building a placeholder variable: word
Loop each character in the input string
and check if character is a letter. Then add letter to the variable "word". Loop until a non-alpha char is encountered.
2. If character is alpha or (alphabet)
Add character to word.
Non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to the "else" part.
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
3. Else
Check if word is greater than "g" alphabetically. Print word and set "word = empty" string.
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
4. Or else
Set word = empty string and build the next word.
else:
word = ""
if word.lower() >= "h":
print("\n", word.upper())
The last "if" is explicitly coded to print the last word if it doesn't end with a non-alpha character like a space or punctuation.
I did this exact same problem. The issue most people are having (and no one seemed to point out) is when you encounter double punctuations or a punctuation followed by a space.
This is the code I used.
phrase = input("Please enter a famous quote: ")
word = ""
for letter in phrase:
if letter.isalpha() is True:
word += letter
elif len(word) < 1: <--- [This is what accounts for double punctuations]
word = ""
elif word[0].lower() >= "g":
print(word)
word = ""
else:
word = ""
print(word) <--- [accounts for last word if not punctuated]
Variable "word" already contains your last word of the phrase but since it does not fulfil the condition to enter the loop it does not gets printed. So you can check the below solution.
phrase = input("Enter a phrase after this: ")
word = ""
for char in phrase:
if char.isalpha():
word += char
else:
if word != "":
if word[0].lower() >= "h":
print(word.upper())
word = ""
else:
word = ""
if word[0].lower() >= "h":
print(word.upper())
This code works for me:
phrase=input("Enter a one sentence quote,non-alpha separate words: ")
word=""
for character in phrase:
if character.isalpha():
word+=character
else:
if word.lower()>="h".lower():
print(word.upper())
word="" -----this code defines the end of a word
else:
word=""
print(word.upper()) ------this will print the last word
I would use regular expressions and list compreshension as shown in the function below.
def words_fromH2Z():
text = input('Enter a quote you love : ')
return [word for word in re.findall('\w+', text) if not word[0] in list('aAbBcCdDeEfFgG')]
When I test the function by putting in the input "I always Visit stack Overflow for Help", I get:
words_fromH2Z()
Enter a quote you love : I always Visit stack Overflow for Help
['I', 'Visit', 'stack', 'Overflow', 'Help']
This worked well for me. I had to add the last two lines of code because without them, it wasn't printing the last word, even if it began with a letter between h and z.
word = ""
quote = input("Enter your quote")
for char in quote:
if char.isalpha():
word += char
elif word[0:1].lower() > "g":
print(word.upper())
word = ""
else:
word = ""
if word[0:1].lower() > "g":
print(word.upper())
famous_quote = input("Enter a one sentence quote:")
current_word = None
for c in famous_quote:
if c.isalpha():
if (c >= 'a') or (c >= 'A'):
if current_word is None:
current_word = c
else:
current_word += c
else:
if current_word is not None:
f = current_word[0]
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print (current_word.upper())
current_word = None
if famous_quote[-1].isalpha():
print (current_word.upper())
Write a function that accepts a string and a character as input and
returns the count of all the words in the string which start with the
given character. Assume that capitalization does not matter here. You
can assume that the input string is a sentence i.e. words are
separated by spaces and consists of alphabetic characters.
This is my code:
def count_input_character (input_str, character):
input_str = input_str.lower()
character = character.lower()
count = 0
for i in range (0, len(input_str)):
if (input_str[i] == character and input_str[i - 1] == " "):
count += 1
return (count)
#Main Program
input_str = input("Enter a string: ")
character = input("Enter character whose occurances are to be found in the given input string: ")
result = count_input_character(input_str, character)
#print(result)
The only part missing here is that how to check if the first word of the sentence is stating with the user given character. consider this output:
Your answer is NOT CORRECT Your code was tested with different inputs. > For example when your function is called as shown below:
count_input_character ('the brahman the master of the universe', 't')
####### Your function returns ############# 2 The returned variable type is: type 'int'
### Correct return value should be ######## 3 The returned variable type is: type 'int'
You function misses the first t because in this line
if (input_str[i] == character and input_str[i - 1] == " "):
when i is 0, then input_str[i - 1] is input_str[-1] which Python will resolve as the last character of the string!
To fix this, you could change your condition to
if input_str[i] == character and (i == 0 or input_str[i - 1] == " "):
Or use str.split with a list comprehension. Or a regular expression like r'(?i)\b%s', with (?i) meaning "ignore case", \b is word boundary and %s a placeholder for the character..
Instead of looking for spaces, you could split input_str on whitespace, this would produce a list of words that you could then test against character. (Pseudocode below)
function F sentence, character {
l = <sentence split by whitespace>
count = 0
for word in l {
if firstchar(word) == character {
count = count + 1
}
}
return count
}
Although it doesn't fix your specific bug, for educational purposes, please note you could rewrite your function like this using list comprehension:
def count_input_character (input_str, character):
return len([x for x in input_str.lower().split() if x.startswith(character.lower())])
or even more efficiently(thanks to tobias_k)
def count_input_character (input_str, character):
sum(w.startswith(character.lower()) for w in input_str.lower().split())
def c_upper(text, char):
text = text.title() #set leading char of words to uppercase
char = char.upper() #set given char to uppercase
k = 0 #counter
for i in text:
if i.istitle() and i == char: #checking conditions for problem, where i is a char in a given string
k = k + 1
return k
The point of the below program so far is to obtain the nearest 1 vowel by iterating from the location of the consonant on the alphabet list until the end of the alphabet list. Ones the loop finds the nearest (to the right) vowel, the loop should stop iterating and assign the index and letter of that vowel to the afterVowel and afterVowelIndex variables. The same should be done with every consonant (that is, if the current iteration of the input (word) is a consonant, we put it on the alphabet list and then iterate though the alphabet list to find the nearest-to-the-right vowel, then stop).
The problem is, it iterates though the alphabet list and outputs all the vowels to the right of the consonant on the alphabet instead of only one.
I tried using break, while loops with conditionals, and other techniques and nothing works, unfortunately.
How can this be fixed?
PS. The print statement below is used to check if one or more vowels are outputted; it is not an actual part of the program.
def rovarspraket(word = raw_input("Please enter a word: ")):
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowels = ['a','e','i','o','u']
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']
#1. Identify if the current element is a consonant, the consonant, and the consonant's index on alphabet list
for character in range(len(word.lower())):
for c in range(len(consonants)):
if word[character] == consonants[c]:
currentConsonant = word[character]
#2. Determine After and Before vowels
#After vowel
for a in range(alphabet.index(word[character]), len(alphabet)):
for aV in range(len(vowels)):
if alphabet[a] == vowels[aV]:
afterVowel = alphabet[a]
afterVowelIndex = a
print afterVowel, afterVowelIndex
I'm hoping I understand your question correctly. If I am, couldn't you solve this with just one boolean flag?
def rovarspraket(word = raw_input("Please enter a word: ")):
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowels = ['a','e','i','o','u']
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']
#1. Identify if the current element is a consonant, the consonant, and the consonant's index on alphabet list
for character in range(len(word.lower())):
for c in range(len(consonants)):
if word[character] == consonants[c]:
currentConsonant = word[character]
#2. Determine After and Before vowels
#After vowel
flag = False
for a in range(alphabet.index(word[character]), len(alphabet)):
for aV in range(len(vowels)):
if alphabet[a] == vowels[aV] and not flag:
afterVowel = alphabet[a]
afterVowelIndex = a
print afterVowel, afterVowelIndex
flag = True
break will exit out of one loop. You need a flag to break out of the second:
done = False
for a in range(alphabet.index(word[character]), len(alphabet)):
for aV in range(len(vowels)):
if alphabet[a] == vowels[aV]:
afterVowel = alphabet[a]
afterVowelIndex = a
print afterVowel, afterVowelIndex
done = True
break
if done:
break