For an assignment have to turn words into the dog lantin version of them, thats not the problem though, they love to find the conditions for our code to fail, so i think they will attempt to trip us up by having different class types in the auto code. My problem is i want to apply my function to a sentence, I can do it for an indivdual word, but I dont know how to have it apply for every word in the sentece. So i have one function here
def dog_latinify_word(word):
"""Takes a word and returns the dog latin version of the word"""
first_letter = word[0]
first_letter.lower()
vowels = ('a','e','i','o','u','1','2','3','4','5',
'6','7','8','9','0')
dogify_vowel = word + 'woof'
dogify_constant = word[1:] + word[0] + "oof"
if word.startswith(vowels):
result = dogify_vowel
elif first_letter != vowels:
result = dogify_constant
return result
but i dont know how to have this function work on every item in a list, because i need to have each word be "dog latinified"
So I have another function to take the sentence that then splits it so each word is its own item in a list, but when I go to call on this function, it only works for class str, and not list. So in my rambling ways can someone point me in the direction of having this function apply into every item in a list, rather than just a string
my code for the secondary function
def dog_latinify_sentence(sentence):
"""translate a sentence into dog latin"""
str_split = sentence.split(' ')
dogify_sentence = dog_latinify_word(str_split)
return dogify_sentence
sorry for the rambling im very tired
You can fix this by just adding a for loop over the list object like this.
def dog_latinify_sentence(sentence):
"""translate a sentence into dog latin"""
str_split = sentence.split(' ')
dogify_sentence = ""
for s in str_split:
dogify_sentence += dog_latinify_word(s)
return dogify_sentence
Above code removes spaces between words. In case you want to preserve spaces,
dogify_sentence = " ".join([dog_latinify_word(s) for s in str_split])
It just gets results from dog_latinify_word() and stitch them back!
Related
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
I'm writing a function where the user inputs a word, then inputs a string, and the function identifies all occurrences and the position of that word in a string (although it's actually converted to a list halfway through).
The code I have currently is only identifying the first occurrence of the word, and none further. It also doesn't identify the word if the word is the first word in the string, returning an empty list. It will also say the word's actual position - 1, as the first word is counted as zero.
I have attempted to curb this problem in two ways, the first of which doing a aString.insert(0, ' '), the second of which doing for i in __: if i == int: i += 1. Neither of these work.
Also, when doing the .insert, I tried putting a character in the space instead of, well, a space (as this part doesn't get printed anyway), but that didn't work.
Here is the code:
def wordlocator(word):
yourWord = word
print("You have chosen the following word: " +yourWord)
aString = input("What string would you like to search for the given word?")
aString = aString.lower()
aString = aString.split()
b = [(i, j) for i, j in enumerate(aString)]
c = [(i, x) for i, x in b if x == yourWord]
return c
The output I'm looking for is that if someone did...
wordlocator("word")
"please input a string generic message" "that is a word"
"4, word"
Currently that would work, but it'd print "3, word". If the string was "that is a word and this is also a word" then it'd ignore the further occurrence of "word".
edit: Got it working now, used a simpler piece of code. Thanks for your help all!
Try this:
def wordlocator(word):
yourWord = word
print("You have chosen the following word: " +yourWord)
aString = raw_input("What string would you like to search for the given word?")
aString = aString.lower()
aString = aString.split()
b = [(i+1, j) for i, j in enumerate(aString) if j == yourWord.lower()]
return b
print wordlocator('word')
note that the list comprehension can be filtered on just the match you are looking for. Actually I just changed it
I get this:
What string would you like to search for the given word?This word is not that word is it?
[(2, 'word'), (6, 'word')]
Note that the index is off by one if that matters, add one to x in the comprehension
A new test:
You have chosen the following word: word
What string would you like to search for the given word?word is the word
[(1, 'word'), (4, 'word')]
I'm doing part of the 'PigLatin translation' program.
Here is the part I'm doing writing right now.
input_str = input("Input a word: ")
consonant_check = 0
while input_str[int(consonant_check)] != 'a' or 'e' or 'i' or 'u':
output_str = input_str[:int(consonant_check)] + input_str[0,int(consonant_check)] + 'ay'
consonant_check = int(consonant_check) + 1
else:
print(output_str)
This part is supposed to check if the word input begins with a consonant. If it does, the program could remove all consonants from the beginning of the word and append them to the end of the word. Then append "ay" to the end of the word.
By collecting information online I had some clues about how to make it happen but I think there are still something wrong with my code.
I would approach it similar to what you intended, resulting in the code below.
In short, check the first character of a string. If it's not a vowel (not in ['a','e','i','o','u']), move the character to the end of the string. Keep doing that until you hit a vowel (so 'string' becomes 'trings' then 'ringst' then 'ingstr' before breaking the loop). Once you finally hit a vowel, you leave the loop, and print the modified string + 'ay'. If the first character is a vowel, you leave the loop and print the string + 'ay'.
There's no need to set a consonant check - you're always checking the first character (0). And there's no need to have two variables - just keep modifying and replacing the original string.
word_string = input("Input a word: ")
while word_string[0] not in ['a','e','i','o','u']:
word_string = word_string[1:] + word_string[0:1]
else:
print(word_string + 'ay')
This isn't a direct answer to your question, but my solution to the pig-latin problem. When learning python, I found that looking at completed examples helped a great deal.
word = "snake"
import string
# Create a list of vowels an consonants
vowels = ['a','e','i','o','u','y']
vowels += [v.upper() for v in vowels]
consonants = [x for x in string.ascii_letters if x not in vowels]
if word[0] in consonants:
# Find the first vowel
idx = min([word.find(v) for v in vowels if word.find(v)>0])
# Split the word at this point and add 'ay'
word = word[idx:] + word[:idx] + 'ay'
print(word)
# Returns "akesnay"
I think your logic is overall a little messed up. I would suggest tackling the problem like this.
1.) Check to see if the first letter is a consonant, if not, do nothing, if so, go to step 2
2.) Find all of the consonants in the word and store them in a list
3.) If it is, remove the vowels from the word, and then append all of the consonant onto the end, followed by 'ay'.
There are infinite ways to actually implement this and I think it would be a good exercise for you to try to implement it yourself, but let me know if you need any more help.
I'm preparing for an exam but I'm having difficulties with one past-paper question. Given a string containing a sentence, I want to find the longest word in that sentence and return that word and its length. Edit: I only needed to return the length but I appreciate your answers for the original question! It helps me learn more. Thank you.
For example: string = "Hello I like cookies". My program should then return "Cookies" and the length 7.
Now the thing is that I am not allowed to use any function from the class String for a full score, and for a full score I can only go through the string once. I am not allowed to use string.split() (otherwise there wouldn't be any problem) and the solution shouldn't have too many for and while statements. The strings contains only letters and blanks and words are separated by one single blank.
Any suggestions? I'm lost i.e. I don't have any code.
Thanks.
EDIT: I'm sorry, I misread the exam question. You only have to return the length of the longest word it seems, not the length + the word.
EDIT2: Okay, with your help I think I'm onto something...
def longestword(x):
alist = []
length = 0
for letter in x:
if letter != " ":
length += 1
else:
alist.append(length)
length = 0
return alist
But it returns [5, 1, 4] for "Hello I like cookies" so it misses "cookies". Why? EDIT: Ok, I got it. It's because there's no more " " after the last letter in the sentence and therefore it doesn't append the length. I fixed it so now it returns [5, 1, 4, 7] and then I just take the maximum value.
I suppose using lists but not .split() is okay? It just said that functions from "String" weren't allowed or are lists part of strings?
You can try to use regular expressions:
import re
string = "Hello I like cookies"
word_pattern = "\w+"
regex = re.compile(word_pattern)
words_found = regex.findall(string)
if words_found:
longest_word = max(words_found, key=lambda word: len(word))
print(longest_word)
Finding a max in one pass is easy:
current_max = 0
for v in values:
if v>current_max:
current_max = v
But in your case, you need to find the words. Remember this quote (attribute to J. Zawinski):
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Besides using regular expressions, you can simply check that the word has letters. A first approach is to go through the list and detect start or end of words:
current_word = ''
current_longest = ''
for c in mystring:
if c in string.ascii_letters:
current_word += c
else:
if len(current_word)>len(current_longest):
current_longest = current_word
current_word = ''
else:
if len(current_word)>len(current_longest):
current_longest = current_word
A final way is to split words in a generator and find the max of what it yields (here I used the max function):
def split_words(mystring):
current = []
for c in mystring:
if c in string.ascii_letters:
current.append(c)
else:
if current:
yield ''.join(current)
max(split_words(mystring), key=len)
Just search for groups of non-whitespace characters, then find the maximum by length:
longest = len(max(re.findall(r'\S+',string), key = len))
For python 3. If both the words in the sentence is of the same length, then it will return the word that appears first.
def findMaximum(word):
li=word.split()
li=list(li)
op=[]
for i in li:
op.append(len(i))
l=op.index(max(op))
print (li[l])
findMaximum(input("Enter your word:"))
It's quite simple:
def long_word(s):
n = max(s.split())
return(n)
IN [48]: long_word('a bb ccc dddd')
Out[48]: 'dddd'
found an error in a previous provided solution, he's the correction:
def longestWord(text):
current_word = ''
current_longest = ''
for c in text:
if c in string.ascii_letters:
current_word += c
else:
if len(current_word)>len(current_longest):
current_longest = current_word
current_word = ''
if len(current_word)>len(current_longest):
current_longest = current_word
return current_longest
I can see imagine some different alternatives. Regular expressions can probably do much of the splitting words you need to do. This could be a simple option if you understand regexes.
An alternative is to treat the string as a list, iterate over it keeping track of your index, and looking at each character to see if you're ending a word. Then you just need to keep the longest word (longest index difference) and you should find your answer.
Regular Expressions seems to be your best bet. First use re to split the sentence:
>>> import re
>>> string = "Hello I like cookies"
>>> string = re.findall(r'\S+',string)
\S+ looks for all the non-whitespace characters and puts them in a list:
>>> string
['Hello', 'I', 'like', 'cookies']
Now you can find the length of the list element containing the longest word and then use list comprehension to retrieve the element itself:
>>> maxlen = max(len(word) for word in string)
>>> maxlen
7
>>> [word for word in string if len(word) == maxlen]
['cookies']
This method uses only one for loop, doesn't use any methods in the String class, strictly accesses each character only once. You may have to modify it depending on what characters count as part of a word.
s = "Hello I like cookies"
word = ''
maxLen = 0
maxWord = ''
for c in s+' ':
if c == ' ':
if len(word) > maxLen:
maxWord = word
word = ''
else:
word += c
print "Longest word:", maxWord
print "Length:", len(maxWord)
Given you are not allowed to use string.split() I guess using a regexp to do the exact same thing should be ruled out as well.
I do not want to solve your exercise for you, but here are a few pointers:
Suppose you have a list of numbers and you want to return the highest value. How would you do that? What information do you need to track?
Now, given your string, how would you build a list of all word lengths? What do you need to keep track of?
Now, you only have to intertwine both logics so computed word lengths are compared as you go through the string.
My proposal ...
import re
def longer_word(sentence):
word_list = re.findall("\w+", sentence)
word_list.sort(cmp=lambda a,b: cmp(len(b),len(a)))
longer_word = word_list[0]
print "The longer word is '"+longer_word+"' with a size of", len(longer_word), "characters."
longer_word("Hello I like cookies")
import re
def longest_word(sen):
res = re.findall(r"\w+",sen)
n = max(res,key = lambda x : len(x))
return n
print(longest_word("Hey!! there, How is it going????"))
Output : there
Here I have used regex for the problem. Variable "res" finds all the words in the string and itself stores them in the list after splitting them.
It uses split() to store all the characters in a list and then regex does the work.
findall keyword is used to find all the desired instances in a string. Here \w+ is defined which tells the compiler to look for all the words without any spaces.
Variable "n" finds the longest word from the given string which is now free of any undesired characters.
Variable "n" uses lambda expressions to define the key len() here.
Variable "n" finds the longest word from "res" which has removed all the non-string charcters like %,&,! etc.
>>>#import regular expressions for the problem.**
>>>import re
>>>#initialize a sentence
>>>sen = "fun&!! time zone"
>>>res = re.findall(r"\w+",sen)
>>>#res variable finds all the words and then stores them in a list.
>>>res
Out: ['fun','time','zone']
>>>n = max(res)
Out: zone
>>>#Here we get "zone" instead of "time" because here the compiler
>>>#sees "zone" with the higher value than "time".
>>>#The max() function returns the item with the highest value, or the item with the highest value in an iterable.
>>>n = max(res,key = lambda x:len(x))
>>>n
Out: time
Here we get "time" because lambda expression discards "zone" as it sees the key is for len() in a max() function.
list1 = ['Happy', 'Independence', 'Day', 'Zeal']
listLen = []
for i in list1:
listLen.append(len(i))
print list1[listLen.index(max(listLen))]
Output - Independence
Need to find the longest word in a string and print that word.
1.) Ask user to enter sentence separated by spaces.
2.)Find and print the longest word. If two or more words are the same length than print the first word.
this is what I have so far
def maxword(splitlist): #sorry, still trying to understand loops
for word in splitlist:
length = len(word)
if ??????
wordlist = input("Enter a sentence: ")
splitlist = wordlist.split()
maxword(splitlist)
I'm hitting a wall when trying to compare the lenghts of words in a sentance. I'm a student who's been using python for 5 weeks.
def longestWord(sentence):
longest = 0 # Keep track of the longest length
word = '' # And the word that corresponds to that length
for i in sentence.split():
if len(i) > longest:
word = i
longest = len(i)
return word
>>> s = 'this is a test sentence with some words'
>>> longestWord(s)
'sentence'
You can use max with a key:
def max_word(splitlist):
return max(splitlist.split(),key=len) if splitlist.strip() else "" # python 2
def max_word(splitlist):
return max(splitlist.split()," ",key=len) # python 3
Or use a try/except as suggested by jon clements:
def max_word(splitlist):
try:
return max(splitlist.split(),key=len)
except ValueError:
return " "
You're going in the right direction. Most of your code looks good, you just need to finish the logic to determine which is the longest word. Since this seems like a homework question I don't want to give you the direct answer (even though everyone else has which I think is useless for a student like you), but there are multiple ways to solve this problem.
You're getting the length of each word correctly, but what do you need to compare each length against? Try to say the problem aloud and how you'd personally solve the problem aloud. I think you'll find that your english description translates nicely to a python version.
Another solution that doesn't use an if statement might use the built-in python function max which takes in a list of numbers and returns the max of them. How could you use that?
You can use nlargest from heapq module
import heapq
heapq.nlargest(1, sentence.split(), key=len)
sentence = raw_input("Enter sentence: ")
words = sentence.split(" ")
maxlen = 0
longest_word = ''
for word in words:
if len(word) > maxlen:
maxlen = len(word)
longest_word = word
print(word, maxlen)