def spin_words(sentence):
for word in sentence.split():
if len(word)>=5:
words = word[::-1]
new_sentence = sentence.replace(word,words)
return new_sentence
spin_words('Hey fellow warriors')
#output is 'Hey fellow sroirraw'
i'm trying to reverse some words in a string that are greater than five characters but i only get one word reversed.
It is easier to store the sentence as an array and change each element independently than modifying the entire sentence on each iteration.
def spin_words(sentence: str):
words = sentence.split()
for idx, word in enumerate(words):
if len(word) >= 5:
words[idx] = word[::-1]
return ' '.join(words)
rev = spin_words('Hey fellow warriors')
print(rev) # Hey wollef sroirraw
Note: This solution does not preserve consecutive spaces or newlines.
You should e.g. move the reversal into the loop itself:
def spin_words(sentence):
for word in sentence.split():
if len(word)>=5:
words = word[::-1]
sentence = sentence.replace(word, words)
return sentence
spin_words('Hey fellow warriors')
You should also be wary of words being parts of other words, e.g. in tester anothertester.
Try this for your code:
def spin_word(this_word):
rotated_list = list(this_word.lower())[::-1]
rotated_word = ''.join(rotated_list)
return rotated_word
def spin_frase(frase):
rotated_frase = []
for word in frase.split():
if len(word) >= 5:
rotated_frase.append(spin_word(word))
else:
rotated_frase.append(word)
print(' '.join(rotated_frase))
if __name__ == '__main__':
spin_frase('Hey fellow warriors')
Related
def spin_words(sentence):
words = sentence.split(' ')
newwords = []
reverse = []
for word in words:
if len(word) < 5:
newwords.append(word)
elif len(word) >= 5:
newword = list(word)
for letter in newword:
reverse.insert(0, letter)
newwords.append(''.join(reverse))
return ' '.join(newwords)
print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))
Working on a Codewars kata for python. Need to take a string and reverse any words that are 5 or more characters long. This code works for single words, but once more than one word is 5 or more characters, it adds those words together for each following word. Ex: my 'Hey fellow warriors' comes back as 'Hey wollef sroirrawwollef' . I am just not sure why is is putting different words together and how to fix it. As far as I know, the for loop in the elif should close out for each word. I know it should be simple, just trying to learn what's happening and why. Thank you!
Simple answer:
You have to clear your reversed word:
def spin_words(sentence):
words = sentence.split(' ')
newwords = []
reverse = []
for word in words:
if len(word) < 5:
newwords.append(word)
elif len(word) >= 5:
newword = list(word)
for letter in newword:
reverse.insert(0, letter)
newwords.append(''.join(reverse))
reverse = [] # Clear the list.
return ' '.join(newwords)
print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))
Output:
emocleW
to
sraWedoC
Hey wollef sroirraw
Nicer answer:
After Ignatius Reilly's comment I made my solution a bit more elegant:
def spin_words(sentence):
words = sentence.split(' ')
newwords = []
for word in words:
if len(word) >= 5:
word = word[::-1]
newwords.append(word)
return ' '.join(newwords)
Here is how I reversed the word.
Output is the same.
Given a sentence string. Write the shortest word in a sentence. If there are several such words, then output the last one. A word is a set of characters that does not contain spaces, punctuation marks and is delimited by spaces, punctuation marks, or the beginning/end of a line.
Input: sentence = “I LOVE python version three and point 10”
Output: "I"
My attempt:
sentence = input("sentence: ")
words = sentence.split()
min_word = None
for word in words:
if len(word) < len(words):
min_word = word
print(min_word)
But output is : 10
Can you help me?
this bug because of if len(word) < len(words):. It can be if len(word) < len(min_word): and to fix len(None) you can use this code:
sentence = input("sentence: ")
words = sentence.split()
min_word = words[0]
for word in words:
if len(word) < len(min_word):
min_word = word
print(min_word)
I have been asked to write a function which returns a string with all the specified punctuations at the beginning and end of the each word removed without affecting those which are within words like ban,ana. How could I do this using loops?
def beautify_sentence(sentence, punctuation):
for element in punctuation:
sentence = sentence.replace(element, "")
return sentence
print(beautify_sentence("?hello !mango! ...and., ban,ana.. yum?? apple!", "!?.,"))
# correct answer = hello mango and ban,ana yum apple
# my answer = hello mango and banana yum apple
This is where you can use str.strip on your individual words:
def beautify_sentence(sentence, punctuation):
return ' '.join([x.strip(punctuation) for x in sentence.split()])
>>> beautify_sentence("?hello !mango! ...and., ban,ana.. yum?? apple!", "!?.,")
hello mango and ban,ana yum apple
Worth mentioning that python has strip, rstrip, and lstrip. lstrip and rstrip remove characters for the start and end of the line.
Using the similar code that you have.
sentance="?hello !mango! ...and., ban,ana.. yum?? apple!"
punctuations="!?.,"
def beautify_sentence(sentence, punctuation):
words = []
for word in sentance.split(' '):
words.append(word.lstrip(punctuations).rstrip(punctuations))
return " ".join(words)
print(beautify_sentence(sentance, punctuations))
But as already mentioned strip will removed front and back.
sentance="?hello !mango! ...and., ban,ana.. yum?? apple!"
punctuations="!?.,"
def beautify_sentence(sentence, punctuation):
words = []
for word in sentance.split(' '):
words.append(word.strip(punctuations))
return " ".join(words)
print(beautify_sentence(sentance, punctuations))
I think this is a learning task. So, I am sharing another approach to solve this problem.
Alternative Approach
We can iterate the sentence and remove any listed punctuation which are not middle of any word.
def beautify_sentence(sentence, punctuation):
beautiful_sentence = ""
for i in range(len(sentence)):
if sentence[i] in punctuation:
# remove punctuation at start and end of a sentence
if i == 0 or i == len(sentence)-1:
continue
# remove punctuation which are not in middle of a word
if not sentence[i-1].isalpha() or not sentence[i+1].isalpha():
continue
beautiful_sentence += sentence[i]
return beautiful_sentence
if __name__ == "__main__":
test_sentence = "?hello !mango! ...and., ban,ana.. yum?? apple!"
test_punctuations = "!?.,"
expected_sentence = "hello mango and ban,ana yum apple"
sentence = beautify_sentence(test_sentence, test_punctuations)
assert sentence == expected_sentence, (expected_sentence, sentence)
This is not tested for all test cases though. You may need to modify it to meet all criterias.
A little bit longer, but I hope you can easily understand the algorithm from this step by step approach.
def beautify(sentence, punctuation):
sen = sentence
punc = punctuation
words = sen.split(" ") # splits into a list of words
ret = [] # return the processed words
for word in words: # process each word one by one
noPuncInTheStart = False
noPuncInTheEnd = False
# don't really mind this. See the break statements!
while (True):
# Check the length of the word to prevent error
# And if there is any punctuation in the beginning
if (len(word) > 0 and not noPuncInTheStart):
if (word[0] in punc): # if the word started by punc
word = word[1:] # remove the first character
else: # there is no any punctuation anymore
noPuncInTheStart = True
else:
# the word is no longger exists :)
# in case the word is all punctuation, no letters, etc
break
if (len(word) > 0 and not noPuncInTheEnd):
if (word[-1] in punc): # check if the end is a punc
word = word[:-1] # remove the end of the character
else:
noPuncInTheEnd = True
else:
break
if (noPuncInTheStart and noPuncInTheEnd):
# there's no longger punc, neither in the beginning
# nor the end
break
ret.append(word) # add the processed word to the `ret` list
ret = " ".join(ret) # join the `ret` list into sentence
return ret
This question already has answers here:
python pig latin converter
(2 answers)
Closed 6 years ago.
I have a python code to translate a one worded string to pyglatin and is as follows:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original)>0 and original.isalpha():
word = original.lower()
first = word[0]
rest = word[1:]
new_word = rest+first+pyg
print new_word
However, I'm stumped on how to translate an entire sentence to Pyglatin. The problem I'm working on has these following conditions: for words that begin with consonants, all initial consonants are moved to the end of the word and 'ay' is appended. For words that begin with a vowel, the initial vowel remains, but 'way' is added to the end of the word.
As an example, the string 'How are you today?' would be 'owhay areway uoyay odaytay?'
Read in a sentence. Break it into individual words (split method). Translate each word to Pig Latin. Concatenate the translations.
Does that get you moving?
Try this. Use split and put it into an empty string.
original = raw_input("Enter Sentence: ")
conversion = ""
for word in original.split():
if len(word)>0 and word.isalpha():
word = word.lower()
first = word[0]
rest = word[1:]
pyg = "ay"
pygword = rest+first+pyg
conversion += pygword + " "
print conversion
Here is my try, but if you are not doing it yourself at least try to understand it. (You are free to ask of course)
This has basic ability to deal with special characters like the "?"
def pygword(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
while word[0] not in vowels:
word = word[1:]+word[0]
return word + "ay"
def pygsentence(sentence):
final = ''
for word in sentence.lower().split(): #split the sentence
#words should only end in symols in correct grammar
if word[-1] in '.,;:!?':
symbol = word[-1]
word = word[:-1]
else:
symbol = ''
if word.isalpha(): #check if word is alphanumerically
final += pygword(word)+symbol+' '
else:
return "There is a strange thing in one of your words."
return final[:-1] #remove last unecessary space
There may be faster, more robust, simpler, better understandable ways to do this, but this how I would start.
Test yields me:
In[1]: pygsentence("How are you today? I am fine, thank you very much good sir!")
Out[1]: 'owhay areway ouyay odaytay? iway amway inefay, ankthay ouyay eryvay uchmay oodgay irsay!'
Your code does not obey the vowel/consonant rule, so I did my own converter for single words.
Just realized that it won't be able to deal with apastrophes in the middle of words (we don't really have theese in german ;) ) so there is a little task left for you.
edit: I did not know in which order you wanted the consonants apended, since that became not clear from your example. So i made an alternative pygword function:
def pygword2(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
startcons = ''
while word[0] not in vowels:
startcons = word[0] +startcons
word = word[1:]
word = word+startcons
return word + "ay"
See the differnece:
In[48]: pygword("street")
Out[48]: 'eetstray'
In[49]: pygword2("street")
Out[49]: 'eetrtsay'
I have created the following code to scramble the letters in a word (except for the first and last letters), but how would one scramble the letters of the words in a sentence; given the input asks for a sentence instead of a word. Thank you for your time!
import random
def main():
word = input("Please enter a word: ")
print(scramble(word))
def scramble(word):
char1 = random.randint(1, len(word)-2)
char2 = random.randint(1, len(word)-2)
while char1 == char2:
char2 = random.randint(1, len(word)-2)
newWord = ""
for i in range(len(word)):
if i == char1:
newWord = newWord + word[char2]
elif i == char2:
newWord = newWord + word[char1]
else:
newWord = newWord + word[i]
return newWord
main()
May I suggest random.shuffle()?
def scramble(word):
foo = list(word)
random.shuffle(foo)
return ''.join(foo)
To scramble the order of words:
words = input.split()
random.shuffle(words)
new_sentence = ' '.join(words)
To scramble each word in a sentence, preserving the order:
new_sentence = ' '.join(scramble(word) for word in input.split())
If it's important to preserve the first and last letters as-is:
def scramble(word):
foo = list(word[1:-1])
random.shuffle(foo)
return word[0] + ''.join(foo) + word[-1]
Split the sentence into a list of words (and some punctuation) with the split method:
words = input().split()
and then do pretty much the same thing you were doing before, except with a list instead of a string.
word1 = random.randint(1, len(words)-2)
...
newWords = []
...
newWords.append(whatever)
There are more efficient ways to do the swap than what you're doing, though:
def swap_random_middle_words(sentence):
newsentence = list(sentence)
i, j = random.sample(xrange(1, len(sentence) - 1), 2)
newsentence[i], newsentence[j] = newsentence[j], newsentence[i]
return newsentence
If what you actually want to do is apply your one-word scramble to each word of a sentence, you can do that with a loop or list comprehension:
sentence = input().split()
scrambled_sentence = [scramble(word) for word in sentence]
If you want to completely randomize the order of the middle letters (or words), rather than just swapping two random letters (or words), the random.shuffle function is likely to be useful.