Python encoding/decoding of str, methods - python

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)

Related

Error trying reversing words in a string using python

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

Iterate through a string and reverse any word with 5 or more characters - Codewars Kata

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.

Find the average length of all words in a sentence

Given a string consisting of words separated by spaces (one or more).
Find the average length of all words.
Average word length = total number of characters in words (excluding spaces) divided by the number of words.
My attempt:
But input is incorrect, can you help me?
sentence = input("sentence: ")
words = sentence.split()
total_number_of_characters = 0
number_of_words = 0
for word in words:
total_number_of_characters += len(sentence)
number_of_words += len(words)
average_word_length = total_number_of_characters / number_of_words
print(average_word_length)
When you're stuck, one nice trick is to use very verbose variable names that match the task description as closely as possible, for example:
words = sentence.split()
total_number_of_characters = 0
number_of_words = 0
for word in words:
total_number_of_characters += WHAT?
number_of_words += WHAT?
average_word_length = total_number_of_characters / number_of_words
Can you do the rest?
I think maybe it should be
for char in word:
Rather than
for char in words:
You may use mean() function to calculate the average.
>>> from statistics import mean()
>>> sentence = 'The quick brown fox jumps over the lazy dog'
>>> mean(len(word) for word in sentence.split())
3.888888888888889
The statistics library was introduced with Python 3.4.
https://docs.python.org/3/library/statistics.html#statistics.mean
There is a simpler way to solve this problem. You can get the amount of words by getting len(words) and the number of letters by taking the original sentence and removing all spaces in it (check the replace() method).
Now your turn to piece these infos together!
Edit: Here's an example:
sentence = input("Sentence: ")
words = len(sentence.split())
chars = len(sentence.replace(" ", ""))
print(chars / words)

How to print words containing specific letters

I have file with words, each line contain a word. What I try do to is ask user for a letters and search for a words with all these letters user has input.
I work on it for a few days but can't make lines 7 and 8 running properly only getting different errors or either is not giving any results.
letters = input('letters: ')
words = open('thesewords').read().splitlines()
print (words)
print(".......................")
for word in words:
if all(letters) in word:
print(word)
You are using all() wrongly.
all(letters) is always a True for string letters, and True in <string> returns you a TypeError.
What you should do is:
all(x in word for x in letters)
So, it becomes:
for word in words:
if all(x in word for x in letters):
print(word)
A more simpler solution if you omit all would be:
letters = input('letters: ')
words_in_file = open('thesewords').read().splitlines()
for word in words_in_file:
if letters in words:
print(word)
Try this:
letters = input('letters: ')
# Make sure you include the full file name and close the string
# Also, .readlines() is simpler than .read().splitlines()
words = open('thesewords.txt').readlines()
# I'll assume these are the words:
words = ['spam', 'eggs', 'cheese', 'foo', 'bar']
print(words)
print(".......................")
for word in words:
if all(x in word for x in letters):
print(word)
As the there are a lot of Syntax Error in the code, I am trying to re-write the code which you have provided drawing a rough sketch of your objective. I hope the code below will satisfy your demand.
letters = input("letters:" )
words = open("thesewords.txt","r")
for word in line.split():
print (word)
print(".......................")
for wrd in words:
if letters in wrd:
print(wrd)
else:
continue

How can I create a code that translates a string sentence to Pyglatin? [duplicate]

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'

Categories