Python loops program - python

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

Related

Issue with analyzing strings in Python for Wordle-esque progam

I've created a function that takes a user-inputted guess, compared it to a hidden word taken randomly from a word doc, and returns a string that indicates if any letters match or are in the word at all. Here is the function:
def wordResults(guess, testGuess):
#guess = user inputted guess
#testGuess = secret word
results = ""
for i in range(5):
#Check if letters at given position match
#in each word, append capital letter if so
if guess[i] == testGuess[i]:
results += guess[i].upper()
#Check if letter at given position is in
#the secret word at all, append lowercase
#letter if so
elif testGuess.find(guess[i]) != -1:
results += guess[i]
#Append underscore if neither condition is met
else:
results += "_"
return results
My issue lies with the elif-statement. I would like it to print a lowercase only if that letter appears in the word, but not if the letter is already in the correct spot. Here is the program running to show what I'm referring to:
(Note: the hidden word is also user-inputted until I get the program working as intended)
For Guess #2, I would like it so that the first 'h' does not show up, since it is indicating the 5th letter in 'conch' that is already confirmed with a capital 'H'. Hope that makes sense.
It's a lot easier to work with a list and then make it a string at the end:
guess = guess.lower()
testGuess = testGuess.lower()
result = []
for i, letter in enumerate(guess):
if letter in testGuess:
if letter == testGuess[i]:
result.append(letter)
else:
result.append(letter.upper())
else:
result.append('_')
for i, letter in enumerate(result):
if letter.upper() in result and result[i] != letter:
result[i] = '_'
return ''.join(result)
For guess two, then the second loop checks if each letter is already in the loop and placed correctly and if it's not in the correct spot, makes it back into an _.

How to find words without certain letters in them and certain letters in the same place that are in specified length

I want to make a hangman game that randomises the word each time you guess a letter, but keeps the wrong letters wrong and the ones you guessed at the same place in the new word. (Like if your word was cat in the beginning and you guessed the 'a'; now the word can be hat.)
I feel like I want to implement too many statements in a while loop and it breaks somehow.
I have this function
def RevealLetters(inputLetter):
LetterPositons.clear()
global WrongGuessCounter
for pos,char in enumerate(Word):
if(char == inputLetter):
LetterPositons.append(pos)
for x in LetterPositons:
if MaskedWord[x] == "_":
MaskedWord[x] = inputLetter
if len(LetterPositons) == 0:
WrongGuessCounter += 1
WrongLetters.append(inputLetter)
Which adds the wrongly guessed letter to a list and those letters should not be used again.
Then in another function I have this while loop which should be able to go thru the list of words and select words that are a specified length (the length was set in another function)
def RandomiseWord():
global Word
print("Randomising Word!")
Word = random.choice(WordBank)
LetterPositons.clear()
while (len(Word) != len(MaskedWord)) and (all(letter in Word for letter in WrongLetters)) :
Word = random.choice(WordBank)
but this somehow gives me words that either contain a letter from the list or a word with a different length.
I tried using if statements inside the while but it broke it further.
And lastly how may I check for words that have the same letters in the same place?
The issue was in my while. it has to be the "Or" statement.
in the end the randomise function looked like this:
def RandomiseWord(): #Randomises the word to add a challange to the game
global Word
global MaskedWord
global WrongLetters
print("Randomising Word!")
Word = random.choice(WordBank)
LetterPositons.clear()
while len(Word) != (len(MaskedWord)+1) or all(letter in Word for letter in WrongLetters) or not all(CheckWord()) :
Word = random.choice(WordBank)
and for finding words with letters in the same place I used:
def CheckWord(): #checks if the word contains the letters in the same place as the hidden one
global MaskedWord
global Word
Match = []
LetterList = list(Word)
LetterList.pop()
for x in range(len(MaskedWord)):
if MaskedWord[x] == "_":
continue
elif MaskedWord[x] == LetterList[x]:
Match.append(True)
else:
Match.append(False)
return Match

How are the letters deleted from this "Vowel eater"?

word = input("enter a word: ")
word = word.upper()
for letter in word:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter =="O":
continue
elif letter == "U":
continue
else:
print(letter)
If I used Joseph as an example, it would return JSPH but I have no idea how the vowels are "deleted"
The letter variable takes one character from the input and compares using the if-else statement. If the character matches the vowels the letter is not printed.
That means the program is only printing the non-vowel characters.
For continue, it essentially skips to the end of the loop and starts the next loop, so following through your loop:
Look at the current letter
If the current letter is a vowel, then continue. (This skips to the next letter in the loop, so the line print(letter) will not be run).
If the current letter is not a vowel, it reaches the else statement and prints the letter.
This means that in the end, the program only prints letters which are not vowels, as whenever a vowel is reached continue is run meaning it skips to the next letter (so the letter is not printed).
Side note: even if you didn't use continue in each elif statement, and used maybe pass instead (which is just a "blank" instruction), the code would still work as by entering one of the if or elif options in the if statement, it means that it won't run any of the other elif or elses afterwards, so the print(letter) wouldn't be called either way. A better way to show the use of continue would be to place the print(letter) outside and after the if statement.
Use regex
word = input("enter a word: ")
word = word.upper()
import re
re.sub("[AEIOU]","", word)

Find position of vowels in a string in Python

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")

How do you begin a new loop when a certain character is found in a previous loop?

Specifically, a user inputs a word. I want to compile a list of all the vowels and consonants used (no repeats, just a note of each one that is used). However, I only want to begin counting consonants AFTER the last vowel in the word is found.
For example, if the input is "hello", it should count e,o, but no consonants, as there are non after the last vowel, with a count vowels=2, consonants=0. If the input is "swarm" it should count a, r, m, vowels=1, consonants=2. "Book" would give you o,k,vowels=1, consonants=1.
There are other conditions I'd like the program to meet, but this one is the first step, and the most important to begin with.
Here's what I have, but it is not working as I need it to (as there is a line for each letter of the alphabet, I will just use quotation marks to show the continuation of the statements):
for i, ch in enumerate(word):
if ch in VOWELS:
if ch=="a" and ch not in VL:
VL=VL+"a"
VC+=1
if ch=="e" and ch not in VL:
VL=VL+"e"
VC+=1
#" " for each other vowel
if ch not in VOWELS:
if ch=="b" and ch not in CL:
CL=CL+"b"
CC+=1
if ch=="c" and ch not in CL:
CL=CL+"c"
CC+=1
#" " for each other consonant
print(VL[1:])
print(VC)
print(CL[1:])
print(CC)
I've tried indenting the consonant section to only begin after the vowel search is done, however, that does not seem to work. I need to index the location of the last vowel, and then start the consonant loop.
As a side not, we're only doing pretty basic commands, such as Boolean, concatenation, and string methods. No dictionaries or lists or things like that. I'm pretty sure there is a simple way to do this, but I can't seem to figure it out.
Instead of only counting consonents after the first vowel, why don't you count every time, but reset the results whenever you find a vowel?
if ch=="a" and ch not in VL:
VL=VL+"a"
VC+=1
CL = "" # add these two lines to each condition
CC = 0
And since I can't resist, the code can be made much shorter and more efficient:
VL = set()
CL = set()
for ch in word:
if ch in VOWELS:
VL.add(ch)
CL = set()
else:
CL.add(ch)
VC = len(VL)
CC = len(CL)
While you're looping over the word, you can also use your i value to loop backwards through its characters. Then, we use a boolean to determine whether our backwards search has hit a vowel yet or not, and only count consonants before the first vowel is hit:
vowels = 'aeiou'
VL=''
VC=0
CL=''
CC=0
word = 'hello'
count_cons = True
for i, c in enumerate(word):
if c in vowels and c not in VL:
VL += c
VC += 1
if word[-i-1] in vowels:
count_cons = False
elif count_cons:
CL += word[-i-1]
CC += 1
print(VL)
print(VC)
print(CL)
print(CC)
This prints:
eo
2
0
If you wanted to shorten this down, you could do something like:
VL = set(c for c in word if c in vowels)
CL = set(c for i, c in enumerate(word)
if c not in vowels and all(x not in vowels for x in word[i+1:]))
VC = len(VL)
CC = len(CL)
print(VL)
print(CL)
print(VC)
print(CC)

Categories

Resources