Problem 1.
This problem provides practice using a while True loop. Write a function named
twoWords that gets and returns two words from a user. The first word is of a
specified length, and the second word begins with a specified letter.
The function twoWords takes two parameters:
an integer, length, that is the length of the first word and
a character, firstLetter, that is the first letter of the second word.
The second word may begin with either an upper or lower case instance of
firstLetter. The function twoWords should return the two words in a list. Use
a while True loop and a break statement in the implementation of twoWords. The
following is an example of the execution of twoWords:
print(twoWords(4, 'B')):
A 4-letter word please two
A 4-letter word please one
A 4-letter word please four
A word beginning with B please apple
A word beginning with B please pear
A word beginning with B please banana
['four', 'banana']
This is what I have so far, but it keeps asking me the first question over again
even if I have the right word length. What am I doing wrong?
def twoWords(length, firstLetter):
wordLen = input('A 4-letter word please ')
while len(wordLen) != int(length):
wordlen = input('A 4-letter word please ')
word = input('A word beginning with ' + firstLetter + ' please ')
while word[0] != firstLetter:
word = input('A word beginning with ' + firstLetter + ' please ')
return[wordLen, word]
def twoWords(length,firstLetter):
firstWord = ""
secondWord= ""
while True:
firstWord = input('A ' + str(length) + '-letter word please.')
if length == len(firstWord):
break
while True:
secondWord = input('A word beginning with ' + firstLetter+ ' please')
if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower():
break
return [firstWord,secondWord]
print(twoWords(4,'B'))
def twoWord(length, firstLetter):
while True:
word1=(input("Enter a "+ str(length)+"-letter word please:"))
if len(word1)==int(length):
break
while True:
word2=input("Please enter the word beginning with "+firstLetter+" please:")
if word2[0].upper()==firstLetter or word2[0].lower()==firstLetter:
break
return word1, word2
print(twoWord(5, 'b'))
Related
Here is my code (a palindrome checker which also checks if the input is a word or not by comparing it with a text file). I am trying to make it so that the code only says it's a word if it's actually a word because now parts of words like 'pr' and 'la' are counting as words.
a = 0
with open('wordlist.txt') as file:
contents = file.read()
print('Hi. This program will check if the word that you enetered is a palindrome.')
while a==0:
wordlist = open('wordlist.txt' , 'r+')
index = 0
letters = []
lettersreversed = []
word = input('Enter a word: ')
wordwithspace = word + '\n'
for i in range(len(word)):
letters.append(word[index])
index = index + 1
index1 = len(word) -1
for i in range(len(word)):
lettersreversed.append(word[index1])
index1 = index1 - 1
if letters == lettersreversed and wordwithspace in contents:
print(word, 'is a palindrome!','\n')
elif letters == lettersreversed and wordwithspace not in contents:
print(word, 'is a palindrome however it is not a word.','\n')
elif letters != lettersreversed and wordwithspace in contents:
print(word, 'is not a palindrome however it is a word.','\n')
else:
print(word, 'is not a palindrome.', '\n')
Your contents = file.read() is one big string. So if you check if a string is in contents then that will be true for any sequence of characters in the string, even if they are not a whole word.
Alternatively,
contents = file.read().split()
Now contents is a list of words, so in contents will only be true for a word in that list.
Even better,
contents = set(file.read().split())
Now it is a set of words, which is much faster to check containment.
I've refactored some of your code. Your issue was checking if it's in contents as it's a huge string. Adding the \n doesn't make sure the word doesn't end with the given word (e.g. toast and ast).
First, load your wordlist as a set:
with open('wordlist.txt') as file:
# Strip all lines off whitespaces, and move them into a set for fast lookup.
wordlist = frozenset(map(str.strip, file))
Then ask for a word:
word = input('Enter a word: ')
Lastly, check if it's a palindrome:
if word == word[::-1] and word in contents:
print("Palindrome and a real word!")
All together:
with open('wordlist.txt') as file:
# Strip all lines off whitespaces, and move them into a set for fast lookup.
wordlist = frozenset(map(str.strip, file))
while True:
word = input('Enter a word: ')
if word == word[::-1]:
if word in contents:
print("Palindrome and a real word!")
else:
print("Palindrome and a fake word!")
else:
if word in contents:
print("Not a palindrome but a real word!")
else:
print("Not a palindrome and not a word!")
def is_palendromic(string: str) -> bool:
"""
| The first `if` statement checks if the
| length of the string is even, if it is
| then it splits the string in half.
| If the string is odd then it still splits
| the string but ignores the middle letter
| as it is erelivant.
"""
if len(string) % 2 == 0:
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
else:
firstpart = string[0:len(string)//2]
secondpart = string[len(string)//2 if len(string)%2 == 0 else ((len(string)//2)+1):]
# will ignore the middle letter if the string is odd
return firstpart[::-1] == secondpart
"""
[:-1] reverses the string and then compares it to the
second part of the string, the doble equals sign
is used to compare the two strings, returning a
blloean
"""
# example
print(is_palendromic('racecar'))
# will print True
print(is_palendromic('racecar_'))
# will print False
This question already has answers here:
Split a string at uppercase letters
(22 answers)
Closed 2 years ago.
I am trying to make a script that will accept a string as input in which all of the words are run together, but the first character of each word is uppercase. It should convert the string to a string in which the words are separated by spaces and only the first word starts with an uppercase letter.
For Example (The Input):
"StopWhateverYouAreDoingInterestingIDontCare"
The expected output:
"Stop whatever you are doing interesting I dont care"
Here is the one I wrote so far:
string_input = "StopWhateverYouAreDoingInterestingIDontCare"
def organize_string():
start_sentence = string_input[0]
index_of_i = string_input.index("I")
for i in string_input[1:]:
if i == "I" and string_input[index_of_i + 1].isupper():
start_sentence += ' ' + i
elif i.isupper():
start_sentence += ' ' + i.lower()
else:
start_sentence += i
return start_sentence
While this takes care of some parts, I am struggling with differentiating if the letter "I" is single or a whole word. Here is my output:
"Stop whatever you are doing interesting i dont care"
Single "I" needs to be uppercased, while the "I" in the word "Interesting" should be lowercased "interesting".
I will really appreciate all the help!
A regular expression will do in this example.
import re
s = "StopWhateverYouAreDoingInterestingIDontCare"
t = re.sub(r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z])', ' ', s)
Explained:
(?<=[a-z])(?=[A-Z]) - a lookbehind for a lowercase letter followed by a lookahead uppercase letter
| - (signifies or)
(?<=[A-Z])(?=[A-Z]) - a lookbehind for a uppercase letter followed by a lookahead uppercase letter
This regex substitutes a space when there is a lowercase letter followed by an uppercase letter, OR, when there is an uppercase letter followed by an uppercase letter.
UPDATE: This doesn't correctly lowercase the words (with the exception of I and the first_word)
UPDATE2: The fix to this is:
import re
s = "StopWhateverYouAreDoingInterestingIDontCare"
first_word, *rest = re.split(r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z])', s)
rest = [word.lower() if word != 'I' else word for word in rest]
print(first_word, ' '.join(rest))
Prints:
Stop whatever you are doing interesting I dont care
Update 3: I looked at why your code failed to correctly form the sentence (which I should have done in the first place instead of posting my own solution :-)).
Here is the corrected code with some remarks about the changes.
string_input = "StopWhateverYouAreDoingInterestingIDontCare"
def organize_string():
start_sentence = string_input[0]
#index_of_i = string_input.index("I")
for i, char in enumerate(string_input[1:], start=1):
if char == "I" and string_input[i + 1].isupper():
start_sentence += ' ' + char
elif char.isupper():
start_sentence += ' ' + char.lower()
else:
start_sentence += char
return start_sentence
print(organize_string())
!. I commented out the line index_of_i = string_input.index("I") as it doesn't do what you need (it finds the index of the first capital I and not an I that should stand alone (it finds the index of the I in Interesting instead of the IDont further in the string_input string). It is not a correct statement.
for i, char in enumerate(string_input[1:], 1) enumerate states the index of the letters in the string starting at 1 (since string_input[1:] starts at index 1 so they are in sync). i is the index of a letter in string_input.
I changed the i's to char to make it clearer that char is the character. Other than these changes, the code stands as you wrote it.
Now the program gives the correct output.
string_input = "StopWhateverYouAreDoingInterestingIDontCare"
counter = 1
def organize_string():
global counter
start_sentence = string_input[0]
for i in string_input[1:]:
if i == "I" and string_input[counter+1].isupper():
start_sentence += ' ' + i
elif i.isupper():
start_sentence += ' ' + i.lower()
else:
start_sentence += i
counter += 1
print(start_sentence)
organize_string()
I made some changes to your program. I used a counter to check the index position. I get your expected output:
Stop whatever you are doing interesting I dont care
s = 'StopWhateverYouAreDoingInterestingIDontCare'
ss = ' '
res = ''.join(ss + x if x.isupper() else x for x in s).strip(ss).split(ss)
sr = ''
for w in res:
sr = sr + w.lower() + ' '
print(sr[0].upper() + sr[1:])
output
Stop whatever you are doing interesting i dont care
I hope this will work fine :-
string_input = "StopWhateverYouAreDoingInterestingIDontCare"
def organize_string():
i=0
while i<len(string_input):
if string_input[i]==string_input[i].upper() and i==0 :
print(' ',end='')
print(string_input[i].upper(),end='')
elif string_input[i]==string_input[i].upper() and string_input[i+1]==string_input[i+1].upper():
print(' ',end='')
print(string_input[i].upper(),end='')
elif string_input[i]==string_input[i].upper() and i!=0:
print(' ',end='')
print(string_input[i].lower(),end='')
if string_input[i]!=string_input[i].upper():
print(string_input[i],end='')
i=i+1
organize_string()
Here is one solution utilising the re package to split the string based on the upper case characters. [Docs]
import re
text = "StopWhateverYouAreDoingInterestingIDontCare"
# Split text by upper character
text_splitted = re.split('([A-Z])', text)
print(text_splitted)
As we see in the output below the separator (The upper case character) and the text before and after is kept. This means that the upper case character is always followed by the rest of the word. The empty first string originates from the first upper case character, which is the first separator.
# Output of print
[
'',
'S', 'top',
'W', 'hatever',
'Y', 'ou',
'A', 're',
'D', 'oing',
'I', 'nteresting',
'I', '',
'D', 'ont',
'C', 'are'
]
As we have seen the first character is always followed by the rest of the word. By combining the two we have the splitted words. This also allows us to easily handle your special case with the I
# Remove first character because it is always empty if first char is always upper
text_splitted = text_splitted[1:]
result = []
for i in range(0, len(text_splitted), 2):
word = text_splitted[i]+text_splitted[i+1]
if (i > 0) and (word != 'I') :
word = word.lower()
result.append(word)
result = ' '.join(result)
split the sentence into individual words. If you find the word "I" in this list, leave it alone. Leave the first word alone. All of the other words, you cast to lower case.
You have to use some string manipulation like this:
output=string_input[0]
for l in string_input[1:]:
if l.islower():
new_s+=l
else:
new_s+=' '+l.lower()
print(output)
So I have a function that takes a string input and turns it into pig latin.
For all words that begin with consonants (everything except vowels), I have to take the first letter of that word and move it to the back and then add "ay" to the word.
For example "like" would become "ikelay".
In my program, the string input given to me is first split and then each element of that newly created list is checked to see if the first character of that element is either a vowel, a consonant, or otherwise.
def simple_pig_latin(input, sep=" ", end="."):
splitinput = input.split(sep)
for i in splitinput:
if splitinput[splitinput.index(i)][0] in ['a','e','i','o','u']:
splitinput[splitinput.index(i)] = str(i) + "way"
elif splitinput[splitinput.index(i)][0] in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']:
splitinput[splitinput.index(i)] = str(i) + "ay"
else:
continue
finalstring = ' '.join(splitinput)
finalstring = finalstring + end
simple_pig_latin("i like this")
Notice in the elif branch, I am supposed to take the first letter of i and put it at the end of that word and add "ay" to it. Given the input string "i like this" I should turn the second word (since like starts with l, making it a consonant) into 'ikelay' How would I rearrange like so that it became ikel?
I tried to keep your structure while still removing the useless code :
def simple_pig_latin(input_text, sep=" ", end="."):
words = input_text.split(sep)
new_words = []
for word in words:
if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
new_words.append(word + "way")
else:
new_words.append(word[1:] + word[0] + "ay")
finalstring = sep.join(new_words)
finalstring = finalstring + end
return finalstring
print simple_pig_latin("i like this")
# iway ikelay histay.
Notes :
Your function needs to return something
It's probably easier to create a new list than to mutate the original one
if i is already a string, there's no need to call str(i)
i is usually used for an integer between 0 and n-1. Not for words.
word[0] is the first letter of your word
word[k:] is word without the first k letters
to simplify your code, I consider that if the first letter isn't a vowel, it must be a consonant.
I call lower() on the first letter in order to check if 'I' is a vowel.
For your question, you could change your code str(i) + "ay" to i[1:] + i[0] + "ay" in your elif branch.
This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
Closed 8 years ago.
So I am writing a program that asks for your input, puts the words of the sentence you entered into a list and makes the words in the statement go trough the while loop one by one.
The while loops works as follows:
if the first letter of a word is a Vowel it print the word + hay.
Ifthe first letter of the word is not a vowel it puts the first letter of the word at the end of the word + ay
the code:
VOWELS = ['a','e','i','o','u']
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
lowercase_phrase = phrase.lower()
word_list = lowercase_phrase.split()
print word_list
x = 0
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay'
else:
print word[1:] + word[0] + 'ay'
x = x+1
pig_latin(raw_input('Enter the sentence you want to translate to Pig Latin, do not use punctation and numbers please.'))
My problem:
If i enter for example: "Hello my name is John" in the_raw input at the end of the code i will get the following output:
ellohay
ymay
amenay
ishay
ohnjay
But i actually want the following output:
ellohay ymay amenay ishay ohnjay
If someone could explain me how to achieve this output it would be appriciated
Save the new words in another list, then at the end:
print(" ".join(pig_latin_words))
Example:
VOWELS = {'a','e','i','o','u'}
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
word_list = phrase.lower().split()
print(word_list)
pig_latin_words = []
for word in word_list:
if word[0] in VOWELS:
pig_latin_words.append(word + "hay")
else:
pig_latin_words.append(word[1:] + word[0] + "ay")
pig_latin_phrase = " ".join(pig_latin_words)
print(pig_latin_phrase)
return pig_latin_phrase
Append a comma (,) at the end of your print statements to avoid the newline:
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay',
else:
print word[1:] + word[0] + 'ay',
x = x+1
I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So for instance:
#here is a variable containing a word:
my_word = "Acrobat"
#letters in vowel as a list
the_vowel = ["a","e","i","o","u"]
How do a check that the first letter in "Acrobat" is one of the vowels in the list? I also need to take into consideration whether it is upper or lowercase?
try my_word[0].lower() in the_vowel
I don't know if it is better than the answers already posted here, but you could also do:
vowels = ('a','e','i','o','u','A','E','I','O','U')
myWord.startswith(vowels)
Here are some hints to help you figure it out.
To get a single letter from a string subscript the string.
>>> 'abcd'[2]
'c'
Note that the first character is character zero, the second character is character one, and so forth.
The next thing to note is that an upper case letter does not compare equal to a lower case letter:
>>> 'a' == 'A'
False
Luckily, python strings have the methods upper and lower to change the case of a string:
>>> 'abc'.upper()
'ABC'
>>> 'a' == 'A'.lower()
True
To test for membership in a list us in:
>>> 3 in [1, 2, 3]
True
>>> 8 in [1, 2, 3]
False
So in order to solve your problem, tie together subscripting to get a single letter, upper/lower to adjust case, and testing for membership using in.
my_word = "Acrobat"
the_vowel = "aeiou"
if myword[0].lower() in the_vowel:
print('1st letter is a vowel')
else:
print('Not vowel')
My code looks like this.
original = raw_input("Enter a word:")
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print word
print first
print "vowel!"
else:
print word
print first
print "consonant
x = (input ("Enter any word: "))
vowel = "aeiouAEIOU"
if x[0] in vowel:
print ("1st letter is vowel: ",x)
else:
print ("1st letter is consonant: ",x)
Here's how I did it since the inputted word needs to be checked first before storing it as a variable:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in ['a','e','i','o','u']:
print "vowel"
else:
print "consonant"
else:
print 'empty'
changes:
if my_word[0] in ('a','e','i','o','u'):
print(' Yes, the first letter is vowel ')
else:
print(' No, the first letter is not vowel ')
So, Here is the simple code for finding out that the first letter is either vowel or not!! If you have any further query in python or js, then comment it down.
import ast,sys
input_str = sys.stdin.read()
if input_str[0] in ['a','e','i','o','u','A','E','I','O','U']:
print('YES')
else:
print('NO')
Here is the solution to the exercise on codecadmy.com:
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print 'vowel'
else:
print 'consonant'
else:
print 'empty'
Will it not be (slightly) faster to define the_vowel as a dictionary than a list?
the_vowel = {"a":1,"e":1,"i":1,"o":1,"u":1}
my_word[0].lower() in the_vowel
anti vowel Function
def anti_vowel(text):
vowel = ["a","e","i","o","u"]
new_text = ''
for char in text:
if char.lower() in vowel:
continue
else:
new_text += char
print new_text
return new_text
x = raw_input("Enter a word: ")
vowels=['a','e','i','o','u']
for vowel in vowels:
if vowel in x:
print "Vowels"
else:
print "No vowels"
This would print out 5 lines, if any of those includes a line that says Vowels then that means there is a vowel. I know this isn't the best way but it works.
Let's do it in more simply way
def check_vowel(s1):
v=['a','e','i','o','u']
for i in v:
if s1[0].lower()==i:
return (f'{s1} start with Vowel word {i}')
else:
return (f" {s1} start with Consonants word {s1[0]}")
print(check_vowel("orange"))
inp = input('Enter a name to check if it starts with vowel : ') *# Here we ask for a word*
vowel = ['A','E','I','O','U', 'a','e','i','o','u'] *# This is the list of all vowels*
if inp[0] in vowel:
print('YES') *# Here with the if statement we check if the first alphabet is a vowel (alphabet from the list vowel)*
else:
print('NO') *# Here we get the response as NO if the first alphabet is not a vowel*
my_word = "Acrobat"
the_vowel = ["a", "e", "i", "o", "u"]
if my_word[0].lower() in the_vowel:
print(my_word + " starts with a vowel")
else:
print(my_word + " doesnt start with a vowel")
input_str="aeroplane"
if input_str[0].lower() in ['a','e','i','o','u']:
print('YES')
else:
print('NO')
Output will be YES as the input string starts with a here.