This is the function:
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This is an exercise on my online course. The objective is to return the first initials of a string capitalized. For example, initials ("Universal Serial Bus") should return "USB".
phrase is a str type object.
str objects can have functions applied to them through their methods. split is a function that returns a list containing multiple str objects. This is stored in words
the for word in words takes each element of words and puts it in the variable word for each iteration of the loop.
The += function adds the first letter of word to result by accessing the first character of the str by using the [0] index of word.
Then the upper function is applied to the result.
I hope this clears it up for you.
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This:
Splits the phrase at every space (" "), with phrase.split(). .split() returns a list which is assigned to words
Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].upper()
return result
print(ShortName("Active Teens Taking Initiative To Understand Driving Experiences"))
Should be: ATTITUDE
def initials(phrase):
words =phrase.split()
result=""+""
for word in words:
result += word[0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
Here is output:
USB
LAN
OS
This:
Splits the phrase at every space (" "+" ") and concatenate next one first letter,with phrase.split() returns a list which is assigned to words Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
strong text
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].uppper()
return result
Related
here is my code
def words_only(sentence):
wordlist1 = sentence.split()
wordlist2 = []
for word in wordlist1:
modified = ''
for char in word:
if char in '_-!,.?":;0123456789':
char = ''
modified += char
wordlist2.append(modified)
return wordlist2
And the description is: words_only receives a string as an argument and returns a list with all the words that were in the sentence. For the purposes of this functions, words are a sequence of only letters (either lower case or upper case
the input is
words_only("two-fold will count as 2 words.")
However, I failed the last test. my output is
['twofold', 'will', 'count', 'as', '', 'words']
the correct output should be
["two", "fold", "will", "count", "as", "words"]
how can I fix my code so that the colon will disappear and "two-fold" will count as 2 words? And there is also an empty string that caused the error.
The problem is that when you have a word that is only formed by the symbols/numbers in your list it will give you an empty string, in the image of your output it seems that you should not add this empty string to your final list. You can fix it by adding an if statement before wordlist2.append(modified_w).
write:
if modified_w:
wordlist2.append(modified_w)
and empty string is considered False so it will not add it, whereas if the symbol/number is within a word it will remove it from the word and then add the corrected word
When using Python, you should utilize its features as much as possible - namely, list comprehension and built-in functions:
[word for word in sentence.split() if word.isalpha()]
This would happen is because you didn't divide the word that conclude str '-'
You can change the code
def words_only(sentence):
wordlist1 = sentence.split()
wordlist2 = []
for word in wordlist1:
modified = ''
for char in word:
if char in '-_0123456789,.[];{}':
if modified: wordlist2.append(modified)
modified = ''
else:
modified += char
if modified: wordlist2.append(modified)
return wordlist2
hope this will be helpful!
I am trying to get the largest word that contains the letter 'f' through a for loop, through my code I tried to make it as simple as possible with a if and and statement. It is however not working as it returns the largest word but not the one that includes the letter f, why is it not working?
def main():
sentence = "Absence makes the heart grow fonder"
letter = "f"
longest_word = get_longest_word(sentence, letter)
print('"' + longest_word + '" is the longest word containing the letter "'
+ letter + '".')
def get_longest_word(sentence, letter):
words_list = sentence.split()
largest = words_list[0]
my_list = []
for word in words_list:
if letter in word and len(word) > len(largest):
largest = word
return largest
main()
The reason is that you initialise largest to words_list[0], which is 'Absence', the longest word in the sentence.
Therefore, even when 'fonder' is reached, even though the first part of your if passes (it contains an 'f'), the second part about length does not.
Personally, I would just do this:
from operator import itemgetter
def get_longest_word(sentence, letter):
words_with_letter = ((word, len(word)) for word in sentence.split() if letter in word)
return max(words_with_letter, key=itemgetter(1))[0]
This converts the sentence into an iterable of tuples where the first element is the word and the second its length, and where all the words already contain the letter in question.
Then, all we need to do is get the word with the longest length i.e. the highest value in the second position.
Output:
"fonder" is the longest word containing the letter "f".
You can approach this much more easily using the in operator:
for word in word_list:
if 'f' in word:
longest_words.append(word)
longest_word = sorted(longest_words)[0]
I am working on a small problem for fun, sent to me by a friend. The problem requires me to populate an array with common words from a text file, and then print all the words from this list containing certain characters provided by the user. I am able to populate my array no problem, but it seems the part of the code that actually compares the two lists is not working. Below is the function I've written to compare the 2 lists.
#Function that prompts user for the set of letters to match and then compares that list of letters to each word in our wordList.
def getLetters():
#Prompt user for list of letters and convert that string into a list of characters
string = input("Enter your target letters: ")
letterList = list(string)
#For each word in the wordList, loop through each character in the word and check to see if the character is in our letter list, if it is increase matchCount by 1.
for word in wordList:
matchCount = 0
for char in word:
if char in letterList:
matchCount+=1
#If matchCount is equal to the length of the word, all of the characters in the word are present in our letter list and the word should be added to our matchList.
if matchCount == len(word):
matchList.append(word)
print(matchList)
The code runs just fine, I don't get any error output, but once the user enters their list of letters, nothing happens. To test I've tried a few inputs matching up with words I know are in my wordList (e.g. added, axe, tree, etc). But nothing ever prints after I enter my letter string.
This is how I populate my wordList:
def readWords(filename):
try:
with open(filename) as file:
#Load entire file as string, split string into word list using whitespace as delimiter
s = file.read()
wordList = s.split(" ")
getLetters()
#Error handling for invalid filename. Just prompts the user for filename again. Should change to use ospath.exists. But does the job for now
except FileNotFoundError:
print("File does not exist, check directory and try again. Dictionary file must be in program directory because I am bad and am not using ospath.")
getFile()
Edit: Changed the function to reset matchCount to 0 before it starts looping characters, still no output.
Your code only needs a simple change:
Pass wordList as a parameter for getLetters. Also if you like you could make a change in order to know if all the letters of the word are in the letter list.
def getLetters(wordList):
string = input("Enter your target letters: ")
letterList = list(string)
matchList = []
for word in wordList:
if all([letter in letterList for letter in word]):
matchList.append(word)
return matchList
And in readWords:
def readWords(filename):
try:
with open(filename) as file:
s = file.read()
wordList = s.split(" ")
result = getLetters(wordList)
except FileNotFoundError:
print("...")
else:
# No exceptions.
return result
Edit: add a global declaration to modify your list from inside a function:
wordList = [] #['axe', 'tree', 'etc']
def readWords(filename):
try:
with open(filename) as file:
s = file.read()
global wordList # must add to modify global list
wordList = s.split(" ")
except:
pass
Here is a working example:
wordList = ['axe', 'tree', 'etc']
# Function that prompts user for the set of letters to match and then compares that list of letters to each word in our wordList.
def getLetters():
# Prompt user for list of letters and convert that string into a list of characters
string = input("Enter your target letters: ")
letterList = list(string)
# For each word in the wordList, loop through each character in the word and check to see if the character is in our letter list, if it is increase matchCount by 1.
matchList = []
for word in wordList:
matchCount = 0
for char in word:
if char in letterList:
matchCount += 1
# If matchCount is equal to the length of the word, all of the characters in the word are present in our letter list and the word should be added to our matchList.
if matchCount == len(word):
matchList.append(word)
print(matchList)
getLetters()
output:
Enter your target letters: xae
['axe']
I'm using Python 3.4 and am getting an error message " 'wordlist is not defined' " in my program. What am I doing wrong? Please respond with code.
The program is to find the longest word:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
def main():
wordlist = input("Enter a list of words seperated by spaces ".split()
word, length = find_longestest_word(wordlist)
print (word, "is",length,"characters long.")
main()
Apart from the problems with your code indentation, your find_longest_word() function doesn't really have any logic in it to find the longest word. Also, you pass it a parameter named a, but you never use a in the function, instead you use wordlist...
The code below does what you want. The len() function in Python is very efficient because all Python container objects store their current length, so it's rarely worth bothering to store length in a separate variable. So my find_longest_word() simply stores the longest word it's encountered so far.
def find_longest_word(wordlist):
longest = ''
for word in wordlist:
if len(word) > len(longest):
longest = word
return longest
def main():
wordlist = input("Enter a list of words separated by spaces: ").split()
word = find_longest_word(wordlist)
print(word, "is" ,len(word), "characters long.")
if __name__ == '__main__':
main()
The line "return word, length" is outside any function. The closest function is "find_longest_word(a)", so if you want it to be a part of that function, you need to indent lines 4-7.
Indentation matters in Python. As the error says, you have the return outside the function. Try:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
def main():
wordlist = input("Enter a list of words seperated by spaces ".split()
word, length = find_longestest_word(wordlist)
print (word, "is",length,"characters long.")
main()
In python the indentation is very important. It should be:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
But because of the function name, I think the implementation is wrong.
I am given a text file that is stored in a list called words_list:
if __name__ = "__main__":
words_file = open('words.txt')
words_list = []
for w in words_file:
w = w.strip().strip('\n')
words_list.append(w)
That's what the list of strings look like (it's a really, really long list of words)
I have to find "all the words" with all of the vowels; so far I have:
def all_vowel(words_list):
count = 0
for w in words_list:
if all_five_vowels(w): # this function just returns true
count = count + 1
if count == 0
print '<None found>'
else
print count
The problem with this is that count adds 1 every time it sees a vowel, whereas I want it to add 1 only if the entire word has all of the vowels.
Simply test if any of your words are a subset of the vowels set:
vowels = set('aeiou')
with open('words.txt') as words_file:
for word in words_file:
word = word.strip()
if vowels.issubset(word):
print word
set.issubset() works on any sequence (including strings):
>>> set('aeiou').issubset('word')
False
>>> set('aeiou').issubset('education')
True
Assuming the word_list variable is an actual list, probably your "all_five_vowels" function is wrong.
This could be an alternative implementation:
def all_five_vowels(word):
vowels = ['a','e','o','i','u']
for letter in word:
if letter in vowels:
vowels.remove(letter)
if len(vowels) == 0:
return True
return False
#Martijn Peters has already posted a solution that is probably the fastest solution in Python. For completeness, here is another good way to solve this in Python:
vowels = set('aeiou')
with open('words.txt') as words_file:
for word in words_file:
word = word.strip()
if all(ch in vowels for ch in word):
print word
This uses the built-in function all() with a generator expression, and it's a handy pattern to learn. This reads as "if all the characters in the word are vowels, print the word." Python also has any() which could be used for checks like "if any character in the word is a vowel, print the word".
More discussion of any() and all() here: "exists" keyword in Python?