how to exchange the middle letter and last letter switched? - python

Ask the user for the input of a word with a minimum of 3 characters. Take that word and exchange the MIDDLE letter with the LAST letter of the word.
If the word is an even number of characters long, take the letter to the right of middle (IE if a word is 6 letters long, you want the 4th character: “switch” is 6 characters and we’d want the ‘t’ as our middle character.
Output to the user their newly rearranged word.
*additional difficulty perform a check that the word is at LEAST 3 letters and display a message that it’s not long enough if something shorter than 3 characters is displayed.strong text
can you guys help me with this?
My code so far:
word=input('Please enter a word with a minimum of 3 characters')
word_length=len(word)
word_middle_index = int(word_length//2)
print('The letter in the middle of the word "'+word+'" is:
word[word_middle_index])
this is how much I've done

this function will complete the task for you:
def switch_mid_and_last(word):
if len(word) < 3:
return("too short word")
else:
mid_letter = len(word)//2
new_word = word[:mid_letter] + word[-1] + word[mid_letter+1:-1] + word[mid_letter]
return(new_word)
the outputs for the next inputs are:
print(switch_mid_and_last("ab"))
>>> too short word
print(switch_mid_and_last("abc"))
>>> acb
print(switch_mid_and_last("abcd"))
>>> abdc
print(switch_mid_and_last("abcde"))
>>> abedc
print(switch_mid_and_last("abcdef"))
>>> abcfed

I've done it so that you can learn how to approach such a problem :
I'd recommend looking into a couple things online :
len function
% operator
[:] operator
For instance :
n % 2 == 0 is True when is even.
"abcd"[1:4] returns "bcd"
word = input("Enter A Word: ")
if len(word) < 3:
print("The word length as to be more than 3 characters")
else:
newWord = ""
middleLetterIndex = 0
lastLetterIndex = len(word) - 1
if len(word) % 2 == 0: # even
middleLetterIndex = int(len(word) / 2) + 1
else:
middleLetterIndex = int(len(word) / 2)
middleLetter = word[middleLetterIndex]
lastLetter = word[lastLetterIndex]
newWord = word[:middleLetterIndex]
newWord += lastLetter
newWord += word[middleLetterIndex+1:lastLetterIndex]
newWord += middleLetter
print(newWord)
Hope this helps you!

For making this easier to grasp, I haven't used any functions, classes, encapsulations or DRY principle here. Since you wanted to show helpful messages in each case, I have also added them.
while True:
word = input("Put a word with at least 3 letters: ")
# check if the word has at least 3 letters
if len(word) < 3:
print("Word needs to be at least 3 letters long!!")
break
# check odd
if not len(word) % 2 == 0:
print("Word length is odd!!!")
# make a list of letters
word_lst = [letter for letter in word]
# mid index
mid_ix = (len(word) - 1) // 2
# last index
last_ix = len(word) - 1
# swap middle and last character
word_lst[mid_ix], word_lst[last_ix] = word_lst[last_ix], word_lst[mid_ix]
# make the list into a string again
word = "".join(word_lst)
print(word)
break
# check even
else:
print("Word length is even!!!")
# make a list of letters
word_lst = [letter for letter in word]
# mid index
mid_ix = (len(word) - 1) // 2 + 1
# last index
last_ix = len(word) - 1
# swap middle and last character
word_lst[mid_ix], word_lst[last_ix] = word_lst[last_ix], word_lst[mid_ix]
# make the list into a string again
word = "".join(word_lst)
print(word)
break

Related

How to check if one character is next to another (Flesch index)?

I'm learning to work with strings and my project is to calculate the number of syllables in a sentence.
I'm given some code that calculates the syllables by adding to the variable, syllables += 1, for each vowel. But the end product is wrong because consecutive vowels should only count as a single +1. For example the word "certain" should return two syllables, not three. There is more to it than this but it's not relevant to my question.
Here is how I solved the problem, with an explanation below:
syllables = 0
vowels = "aeiouAEIOU"
vowelContainer = "" # Part of my added code for solution. Create some container to hold
# a representation of consecutive vowels.
for word in text.split():
for vowel in vowels:
syllables += word.count(vowel)
for ending in ['es', 'ed', 'e']:
if word.endswith(ending):
syllables -= 1
if word.endswith('le'):
syllables += 1
for vowel in word: # My added code for solution: rest of lines that follow
if vowel == vowel in vowels: # I fill in the container with Ts and Fs to create a string
vowelContainer += "T" # that I can then check for consecutive vowels.
else:
vowelContainer += "F"
count2ConsecutiveVowels = vowelContainer.count("TT") # I count how many times there are two
count3ConsecutiveVowels = vowelContainer.count("TTT") # or three vowels in the word.
syllables = syllables - count2ConsecutiveVowels - count3ConsecutiveVowels # I subtract the count
vowelContainer = "" # from total syllables
# At the end of the loop I empty the container for the next word.
I managed to come up with a solution, but it is messy. Is there a simpler way to do this?
I think this code should work:
vowels = "aeiouAEIOU"
text = "certain"
syllables_count = 0
if len(text) == 1:
if text[0] in vowels:
syllables_count += 1
else:
for i in range(len(text) - 1):
if text[i] in vowels and text[i+1] not in vowels:
syllables_count += 1
elif text[i] in vowels and i+1 == len(text) - 1:
syllables_count += 1
print(syllables_count)
In order to solve the problem of consecutive vowels you mentioned above, and get the correct number of syllables, I suggest using a regular expression as in the following example:
import re # put in the beginning to import regular expression module
word='certaaaaiin' # just for example
a=re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',word)
syllables =len(a)
print(syllables)
# output is 2
In this method, any number of consecutive vowels is considered as one in counting
in the regular expression [aeiouAEIOU](?![aeiouAEIOU]), it selects any vowel in the list, in case of that vowel does not have another one after.
vowels = "aeiou"
count = 0
with open("/home/doofinschmurts/PycharmProjects/Practice_001/text.txt", "r") as text:
text = text.read()
for character in range(len(text) - 1):
if text[character] in vowels and text[(character + 1)] not in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character + 2] in vowels and text[character - 1] not in vowels:
count += 1
print(count)
I'm new to coding but this script works and the main "jist" is in the long if statements. This wont be the best answer; however, if any veterans wouldn't mind critiquing me also.
Every time you encounter a vowel, you need to increment the syllables counter by 1. Otherwise, you can ignore it.
Try this and see if this meets your needs.
text = input('Enter your word(s) :')
syllables = 0
vowels = "aeiou" #no need to check for upper and lower
for word in text.split():
vowel_found = False #initialize vowel_found to False and check if the world has vowels
for char in word: #iterate thru each char in the word
if not vowel_found and char.lower() in vowels: #for every new vowel found, increment syllables by 1
syllables +=1
vowel_found = True
else:
vowel_found = False #reset to increment counter again
print (syllables)
Here's the output I got:
Enter your word(s) :syllables
2
Enter your word(s) :certain
2
Enter your word(s) :book
1
Enter your word(s) :case
2
Enter your word(s) :Heart
1
Let me know if this code fails. I would like to improve this.

How do I choose 2 or more letters in a word?

Basically my plan was to return text with random-sized letters in words i.e. "upper" or "lower". The script is working, though it seems raw (I am a Beginner and I'd appreciate some corrections from You).
The problem is:
It is not consistent. With that said, it can print word 'about' even if it should be 'About' or something similar.
I want to be sure that the maximum of UPPER or lower letters in a row do not exceed 3 letters. and I don't know how to do it.
Thank you in advance.
#!/usr/bin/env python3
import random
message = input()
stop = ''
def mocking(message):
result = ''
for word in message:
for letter in word:
word = random.choice(random.choice(letter.upper()) + random.choice(letter.lower()))
result += word
return result
while stop != 'n':
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
You need to split the input into words, decide how many positions inside the word you want to change (minimum 3 or less if the word is shorter).
Then generate 3 unique positions inside the word (via random.sample) to change, check if upper then make lower else make upper. Add to resultlist and join words back together.
import random
message = "Some text to randomize"
def mocking(message):
result = []
for word in message.split():
len_word = len(word)
# get max 3 random positions
p = random.sample(range(len_word),k = min(len_word,3))
for position in p:
l = word[position]
if l.isupper():
word = word[:position] + l.lower() + word[position+1:]
else:
word = word[:position] + l.upper() + word[position+1:]
result.append(word)
return ' '.join(result)
while True:
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
See Understanding slice notation for slicing
At most 3 modifications? I would go with something like this.
def mocking(message):
result = ''
randomCount = 0
for word in message:
for letter in word:
newLetter = random.choice( letter.upper() + letter.lower() )
if randomCount < 3 and newLetter != letter:
randomCount += 1
result += newLetter
else:
result += letter
randomCount = 0
return result
If the random choice has modified the letter then count it.

Issues when grabbing words of a specific length from a txt file in python

The main confusion I am having with my code is that I am aiming to find all the words in the dictionary.txt of a particular length containing just a single vowel (defined as a, e, i, o and u) that does not have a particular letter in it. However, it does not work correctly. For example, if I am looking for all the words of length 9 containing just a single vowel that does not have letter ‘t’ in it, the
program below tells me “There are no words that fit this criteria”. But there should be two
words in the file satisfying the above criteria: “lynchings”, and “lynchpins”.
My dictionary is located at https://filebin.net/96k7kso4i6nxcd2n/dictionary.txt?t=x9ujn62v
def onevowel(file):
length = int(input("Please enter the word length you are looking for: "))
letter = input("Please enter the letter you'd like to exclude: ")
wordnum = 0
for word in file:
word = word.strip()
if len(word) == length:
count = 0
for char in word:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):
count += 1
if count == 1:
flag = 1
word_str = ""
for char in word:
if char == letter:
flag = 0
else:
word_str += char
if flag == 1:
print (word_str)
wordnum += 1
if wordnum == 0:
print ("There are no words that fit this criteria.")
if __name__ == "__main__":
my_file = open("dictionary.txt","r")
onevowel(my_file)
my_file.close()
Replace char=='a' and char=='e' and char=='i' and char=='o' and char=='u' (which is never true) with char in "aeoui".
Because you want only a single vowel, use the or condition rather than and in this line:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):

Filter words in a sentence that begin with a certain range of letters

My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.
This is my code so far, however it still prints words which begin with "g" and does not print the last word.
famous_quote = input("Enter a one sentence quote: ").lower()
word = ""
for ltr in famous_quote:
if ltr.isalpha() == True:
word = word + ltr
else:
if word > "g":
print(word)
word = ""
else:
word = ""
I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.
Sample input:
Wheresoever you go, go with all your heart
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Algorithm I've come up with:
- split the words by building a placeholder variable: word
- Loop each character in the input string
- check if character is a letter
- add a letter to word each loop until a non-alpha char is encountered
- if character is alpha
- add character to word
- non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
- else
- check if word is greater than "g" alphabetically
- print word
- set word = empty string
- or else
- set word = empty string and build the next word
- Hint: use .lower()
You can define a neat little generator to split your sentence into words and compare the first letter of each.
def filter_words(sentence, lo, hi):
lo, hi = map(str.upper, (lo, hi))
words = sentence.upper().split()
for word in words:
if lo <= word[0] <= hi:
yield word
sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')
WHERESOEVER
YOU
WITH
YOUR
HEART
This is how I approached this problem. It gave me a hard time since I am a beginer. But it seems to work fine.
quote = "quote goes here"
word = ""
for letter in quote:
if letter.isalpha():
word += letter
else:
if word > "":
print(word.upper())
word = ""
else:
word = ""
print(word.upper())
I added the space to the user_input and also used the word > 'h'. Below is how it looks:
user_input = input('Enter a phrase: ').lower()
user_input += ' '
word = ''
for char in user_input:
if char.isalpha():
word += char
else:
if word > 'h':
print(word.upper())
word = ''
else:
word = ''
This code worked for me...
The task is: Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z
I was making the mistake of using word > "g" before, which needs to be replaced by word > "h".
Also, you need to add the last print command in order to print the last word in case the phrase does not end with a punctuation (as in the given example)
phrase = input ("Please enter a phrase: ").lower()
word = ""
for letter in phrase:
if letter.isalpha():
word += letter
else:
if(word > "h" ):
print(word)
word = ""
else:
word = ""
if word.lower() > 'h':
print(word)
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.
The two issues you've highlighted is that you are comparing the whole word instead of just the first character.
Simply change:
if word > "g":
To:
if word and word[0] > "g":
And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:
if word:
print(word)
You may note the output is all uppercase, so .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:
famous_quote = input("Enter a one sentence quote: ")
...
if word and word[0].lower() > "g":
Note: You can simplify your else: condition:
else:
if word and word[0] > "g":
print(word)
word = ""
You stated that you are not allowed to use the split() method. I am not sure what you can use, so here's a solution (not the optimal one).
famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
if current_word is None:
current_word = c # start a new word
else:
current_word += c # append a new letter to current word
else:
if current_word is not None:
f = current_word[0] # first letter
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print(current_word)
current_word = None
Here is a sample run of the program. It preserves lowercase and uppercase. It also splits words on any non-ASCII character.
Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you
Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.
Assuming that the famous quote contains only spaces as word separator, this should do the job:
words = input("Enter a one sentence quote: ").lower().split()
for word in words:
if word[0] > 'g':
print("{w} ".format(w = word))
split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.
print() can be used in a lot of ways, due to python's history with this function.
You can .join() the list (getting a string as result) and print it:
print(" ".join(words))
you can also print with concatenations (considered ugly):
print(word+" ")
or you can use formatted printing, which I do use a lot for readibility:
print("{w} ".format(w = word))
interprets "{w}" and replaces it with word wherever "{w}" appears.
Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).
1. Split the words by building a placeholder variable: word
Loop each character in the input string
and check if character is a letter. Then add letter to the variable "word". Loop until a non-alpha char is encountered.
2. If character is alpha or (alphabet)
Add character to word.
Non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to the "else" part.
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
3. Else
Check if word is greater than "g" alphabetically. Print word and set "word = empty" string.
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
4. Or else
Set word = empty string and build the next word.
else:
word = ""
if word.lower() >= "h":
print("\n", word.upper())
The last "if" is explicitly coded to print the last word if it doesn't end with a non-alpha character like a space or punctuation.
I did this exact same problem. The issue most people are having (and no one seemed to point out) is when you encounter double punctuations or a punctuation followed by a space.
This is the code I used.
phrase = input("Please enter a famous quote: ")
word = ""
for letter in phrase:
if letter.isalpha() is True:
word += letter
elif len(word) < 1: <--- [This is what accounts for double punctuations]
word = ""
elif word[0].lower() >= "g":
print(word)
word = ""
else:
word = ""
print(word) <--- [accounts for last word if not punctuated]
Variable "word" already contains your last word of the phrase but since it does not fulfil the condition to enter the loop it does not gets printed. So you can check the below solution.
phrase = input("Enter a phrase after this: ")
word = ""
for char in phrase:
if char.isalpha():
word += char
else:
if word != "":
if word[0].lower() >= "h":
print(word.upper())
word = ""
else:
word = ""
if word[0].lower() >= "h":
print(word.upper())
This code works for me:
phrase=input("Enter a one sentence quote,non-alpha separate words: ")
word=""
for character in phrase:
if character.isalpha():
word+=character
else:
if word.lower()>="h".lower():
print(word.upper())
word="" -----this code defines the end of a word
else:
word=""
print(word.upper()) ------this will print the last word
I would use regular expressions and list compreshension as shown in the function below.
def words_fromH2Z():
text = input('Enter a quote you love : ')
return [word for word in re.findall('\w+', text) if not word[0] in list('aAbBcCdDeEfFgG')]
When I test the function by putting in the input "I always Visit stack Overflow for Help", I get:
words_fromH2Z()
Enter a quote you love : I always Visit stack Overflow for Help
['I', 'Visit', 'stack', 'Overflow', 'Help']
This worked well for me. I had to add the last two lines of code because without them, it wasn't printing the last word, even if it began with a letter between h and z.
word = ""
quote = input("Enter your quote")
for char in quote:
if char.isalpha():
word += char
elif word[0:1].lower() > "g":
print(word.upper())
word = ""
else:
word = ""
if word[0:1].lower() > "g":
print(word.upper())
famous_quote = input("Enter a one sentence quote:")
current_word = None
for c in famous_quote:
if c.isalpha():
if (c >= 'a') or (c >= 'A'):
if current_word is None:
current_word = c
else:
current_word += c
else:
if current_word is not None:
f = current_word[0]
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print (current_word.upper())
current_word = None
if famous_quote[-1].isalpha():
print (current_word.upper())

Python 3.2 - Converting words to lower case & number of palindromes in the list of words that have at least 3 letters

I have a random file of words and some of them are palindromes and some are not. Some of those palindromes are 3 or more letters long. How do I count them? I'm wondering how to make the conditions better. I thought I could just length but I keep getting 0 as my answer, which I know is not true because I have the .txt file.
Where am I messing up?
number_of_words = []
with open('words.txt') as wordFile:
for word in wordFile:
word = word.strip()
for letter in word:
letter_lower = letter.lower()
def count_pali(wordFile):
count_pali = 0
for word in wordFile:
word = word.strip()
if word == word[::-1]:
count_pali += 1
return count_pali
print(count_pali)
count = 0
for number in number_of_words:
if number >= 3:
count += 1
print("Number of palindromes in the list of words that have at least 3 letters: {}".format(count))
You are looping through number_of_words in order to calculate count, but number_of_words is initialized to an empty list and never changed after that, hence the loop
for number in number_of_words:
if number >= 3:
count += 1
will execute exactly 0 times
Your code looks good right up until the loop:
for number in number_of_words:
if number >= 3:
count += 1
There is a problem in the logic here. If you think about the data structure of number_of_words, and what you are actually asking python to compare with the 'number >= 3' condition, then I think you will figure your way through it nicely.
--- revised look:
# Getting the words into a list
# word_file = [word1, word2, word3, ..., wordn]
word_file = open('words.txt').readlines()
# set up counters
count_pali, high_score = 0, 0
# iterate through each word and test it
for word in word_file:
# strip newline character
word = word.strip()
# if word is palindrome
if word == word[::-1]:
count_pali += 1
# if word is palindrome AND word is longer than 3 letters
if len(word) > 3:
high_score += 1
print('Number of palindromes in the list of words that have at least 3 letter: {}'.format(high_score))
NOTES:
count_pali: counts the total number of words that are palindromes
high_score: counts the total number of palindromes that are longer than 3 letters
len(word): if word is palindrome, will test the length of the word
Good luck!
This doesn't directly answer your question, but it might help to understand some of the problems that we have run into here. Mostly, you can see how to add to a list, and hopefully see the difference between getting the length of a string, list and integer (which you actually can't do!).
Try running the code below, and examine what is happening:
def step_forward():
raw_input('(Press ENTER to continue...)')
print('\n.\n.\n.')
def experiment():
""" Run a whole lot experiments to explore the idea of lists and
variables"""
# create an empty list, test length
word_list = []
print('the length of word_list is: {}'.format(len(word_list)))
# expect output to be zero
step_forward()
# add some words to the list
print('\nAdding some words...')
word_list.append('Hello')
word_list.append('Experimentation')
word_list.append('Interesting')
word_list.append('ending')
# test length of word_list again
print('\ttesting length again...')
print('\tthe length of word_list is: {}'.format(len(word_list)))
step_forward()
# print the length of each word in the list
print('\nget the length of each word...')
for each_word in word_list:
print('\t{word} has a length of: {length}'.format(word=each_word, length=len(each_word)))
# output:
# Hello has a length of: 5
# Experimentation has a length of: 15
# Interesting has a length of: 11
# ending has a length of: 6
step_forward()
# set up a couple of counters
short_word = 0
long_word = 0
# test the length of the counters:
print('\nTrying to get the length of our counter variables...')
try:
len(short_word)
len(long_word)
except TypeError:
print('\tERROR: You can not get the length of an int')
# you see, you can't get the length of an int
# but, you can get the length of a word, or string!
step_forward()
# we will make some new tests, and some assumptions:
# short_word: a word is short, if it has less than 9 letters
# long_word: a word is long, if it has 9 or more letters
# this test will count how many short and long words there are
print('\nHow many short and long words are there?...')
for each_word in word_list:
if len(each_word) < 9:
short_word += 1
else:
long_word += 1
print('\tThere are {short} short words and {long} long words.'.format(short=short_word, long=long_word))
step_forward()
# BUT... what if we want to know which are the SHORT words and which are the LONG words?
short_word = 0
long_word = 0
for each_word in word_list:
if len(each_word) < 9:
short_word += 1
print('\t{word} is a SHORT word'.format(word=each_word))
else:
long_word += 1
print('\t{word} is a LONG word'.format(word=each_word))
step_forward()
# and lastly, if you need to use the short of long words again, you can
# create new sublists
print('\nMaking two new lists...')
shorts = []
longs = []
short_word = 0
long_word = 0
for each_word in word_list:
if len(each_word) < 9:
short_word += 1
shorts.append(each_word)
else:
long_word += 1
longs.append(each_word)
print('short list: {}'.format(shorts))
print('long list: {}'.format(longs))
# now, the counters short_words and long_words should equal the length of the new lists
if short_word == len(shorts) and long_word == len(longs):
print('Hurray, its works!')
else:
print('Oh no!')
experiment()
Hopefully, when you look through our answers here, and examine the mini-experiment above, you will be able to get your code to do what you need it to do :)

Categories

Resources